<template>
  <setting-public-view current="taskSet" :nav="taskNav">
    <div class="setting-box-warp task-setting-box-warp">

      <!-- 工单操作原因设置 -->
      <div class="setting-box">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.taskOperateReasonSetting')}}</p>
        </div>

        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="24">
              <p class="item-message">{{$t('task.tip.taskSettingTip1')}}</p>
              <el-table
                class="item-table"
                :data="customTaskExceptionFieldConfig"
                border
                :header-cell-style="{'background-color': '#FAFAFA'}"
                style="width: 100%">
                <el-table-column
                  prop="exceptionName"
                  :label="$t('task.setting.taskSetting.circulationNode')"
                  width="90">
                  <template slot-scope="scope">
                    {{getTaskExceptionStateLabel(scope.row.exceptionName)}}
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('task.setting.taskSetting.operateReason')">
                  <template slot-scope="scope">
                    <div v-if="scope.row.reason">
                      <span class="item-tag" v-for="v in scope.row.reason.slice(0,5)" :key="v">
                        {{v}}
                      </span>
                      <template v-if="scope.row.reason.length > 5">
                        <el-tooltip :content="scope.row.lastList.join(',')" placement="top">
                          <span class="item-tag">...</span>
                        </el-tooltip>
                      </template>
                    </div>
                    <p class="item-text-center" v-else>/</p>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('common.base.operation')"
                  width="70">
                  <template slot-scope="scope">
                    <el-button type="text" @click="checkCus=scope.row;taskExceptionDialog=true;" v-if="scope.row.reason">{{$t('common.base.edit')}}</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>

        <!-- 工单操作原因设置 atart -->
        <base-modal :title="`${is_Show === 'next' ? $t('task.setting.taskSetting.editRemind') : $t('task.setting.taskSetting.taskOperateReasonEdit')}`" @closed="is_Show='next'" :show.sync="taskExceptionDialog" width="700px" class="setting-public-dialog">
          <div class="modal_box">
            <div v-if="is_Show == 'next'">
              <p>{{$t('task.tip.taskSettingTip2')}}</p>
              <p>{{$t('task.tip.taskSettingTip3')}}</p>
              <p>{{$t('task.tip.taskSettingTip4')}}</p>
              <p>{{$t('task.tip.taskSettingTip5')}}</p>
            </div>
            <div v-else>
              <p>{{$t('task.tip.taskSettingTip6')}}</p>
              <el-input v-model="tValue" type="textarea" :rows="6"></el-input>
              <div class="set-task-operation-required">
                <el-tooltip :content="$t('task.tip.taskSettingTip7')" placement="bottom" >
                  <span>{{$t('task.setting.taskSetting.setAsRequired')}} <i class="el-icon-info"></i> ：</span>
                </el-tooltip>
                <el-switch
                  v-model="setTaskOperationRequired"
                  :active-color="getThemeColor">
                </el-switch>
              </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <base-button type="ghost" @event="taskExceptionDialog = false">{{$t('common.base.cancel')}}</base-button>
            <base-button type="primary" @event="taskExceptionBtn('next')" v-if="is_Show == 'next'">{{$t('common.task.button.continue')}}</base-button>
            <base-button type="primary" @event="taskExceptionBtn('save')" v-else>{{$t('common.base.makeSure')}}</base-button>
          </div>
        </base-modal>
        <!-- 工单操作原因设置 end -->
      </div>

      <!-- 异常工单设置 -->
      <div class="setting-box">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.exceptionTaskSetting')}}</p>
        </div>

        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.exceptionTaskNodeSetting')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text1')}}</p>
              <div class="setting—box-multiple">
                <el-select class="multiple-select" v-model="taskExceptionNodeConfigSelect" multiple :placeholder="$t('task.setting.taskSetting.placeholder1')">
                  <el-option
                    v-for="item in taskExceptionNodeConfigList"
                    :key="item.taskExceptionNodeName"
                    :label="getTaskExceptionStateLabel(item.chineseName)"
                    :value="item.taskExceptionNodeName">
                  </el-option>
                </el-select>
                <el-button class="multiple-save" type="primary" @click="saveAbnormalSelect('taskExceptionNode')" :disabled="!isAbnormalTaskNodeChange">{{$t('common.base.save')}}</el-button>
              </div>  
            </el-col>
          </el-row>

          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.exceptionTaskStatisticsRangeSetting')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text2')}}</p>
              <div class="setting—box-multiple">
                <el-select class="multiple-select" v-model="AbnormalSelect" multiple :placeholder="$t('task.setting.taskSetting.placeholder2')">
                  <el-option
                    v-for="item in AbnormalList"
                    :key="item.taskExceptionRangeName"
                    :label="getTaskExceptionRangeLabel(item.chineseName)"
                    :value="item.taskExceptionRangeName">
                  </el-option>
                </el-select>
                <el-button class="multiple-save" type="primary" @click="saveAbnormalSelect('taskExceptionRange')" :disabled="!isAbnormaChange">{{$t('common.base.save')}}</el-button>
              </div>  
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 工单池设置 -->
      <div class="setting-box module-scroll-taskPool">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.poolSetting')}}</p>
        </div>

        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.enablePool')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text3')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskPoolOn"
                  @change="(value)=>{saveTaskAct('taskPoolOn',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskPoolOn?$t('common.base.enable'):$t('common.base.disable')">
                </el-switch>
            </el-col>
          </el-row>
          <div v-show="taskPoolOn">
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">
                  <el-tooltip :content="$t('task.tip.taskSettingTip8')" placement="top">
                    <span>{{$t('task.setting.taskSetting.poolNotificationDistanceRange')}} <i class="el-icon-info"></i></span>
                  </el-tooltip>
                </p>
                <p class="item-text">
                  <span>{{$t('task.setting.taskSetting.text4')}}</span>
                  <!-- maxRangeKm 这个值后端会再乘1000存起来，导致int型存不下，所以限制最大长度为6 -->
                  <el-input v-model="maxRangeKm" @change="(value)=>{taskConfigChange('maxRangeKm',value)}" class="item-input-num" size="mini" maxlength="6"></el-input>
                  <span>{{$t('task.setting.taskSetting.text5')}}</span>
                </p>
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">
                  <el-tooltip :content="$t('task.setting.taskSetting.placeholder3')" placement="top" >
                    <span>{{$t('task.setting.taskSetting.pollNotificationUserLimit')}} <i class="el-icon-info"></i></span>
                  </el-tooltip>
                </p>
                <p class="item-text">
                  <span>{{$t('task.setting.taskSetting.text6')}}</span>
                  <el-input v-model="maxUsers" @change="(value)=>{taskConfigChange('maxUsers',value)}" class="item-input-num" size="mini" maxlength="5"></el-input>
                  <span>{{$t('task.setting.taskSetting.text7')}}</span>
                </p>
              </el-col>
              <el-col :span="8">
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">{{$t('task.setting.taskSetting.poolOverTimeSetting')}}</p>
                <p class="item-text">
                  <span>{{$t('task.setting.taskSetting.text8')}}</span>
                  <el-input v-model="overTime" @change="(value)=>{taskConfigChange('overTime',value)}" class="item-input-num" size="mini" maxlength="50"></el-input>
                  <span>{{$t('task.setting.taskSetting.text9')}}</span>
                </p>
              </el-col>
              <el-col :span="8">
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text10')}}</p>
                <p class="item-text">{{$t('task.setting.taskSetting.text11')}}</p>
              </el-col>
              <el-col :span="8">
                <el-switch
                    class="setting—box-switch"
                    v-model="byTag"
                    @change="(value)=>{saveTaskPoolSetting('byTag',value)}"
                    :active-color="getThemeColor" 
                    :active-text="byTag?$t('common.base.enable'):$t('common.base.disable')">
                </el-switch>
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">{{$t('task.setting.taskSetting.text12')}}</p>
                <p class="item-text">{{$t('task.setting.taskSetting.text13')}}</p>
              </el-col>
              <el-col :span="8">
                <el-switch
                    class="setting—box-switch"
                    v-model="reallotToPool"
                    @change="(value)=>{saveTaskPoolSetting('reallotToPool',value)}"
                    :active-color="getThemeColor" 
                    :active-text="reallotToPool?$t('common.base.enable'):$t('common.base.disable')">
                </el-switch>
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">
                  <el-tooltip :content="$t('task.setting.taskSetting.placeholder4')" placement="top" >
                    <span>{{$t('task.setting.taskSetting.text14')}}<i class="el-icon-info"></i></span>
                  </el-tooltip>
                </p>
                <p class="item-text">
                  <span>{{$t('task.setting.taskSetting.text15')}}</span>
                  <el-input v-model="singleDayMaxOrderNum" @change="(value)=>{taskConfigChange('singleDayMaxOrderNum',value)}" class="item-input-num" size="mini" maxlength="5"></el-input>
                  <span>{{$t('task.setting.taskSetting.text16')}}</span>
                </p>
              </el-col>
              <el-col :span="8">
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">{{$t('task.setting.taskSetting.text17')}}</p>
                <p class="item-text">{{$t('task.setting.taskSetting.text18')}}</p>
              </el-col>
              <el-col :span="8">
                <el-switch
                  v-if="overTime>0||isNotice"
                  class="setting—box-switch"
                  v-model="isNotice"
                  @change="(value)=>{saveTaskPoolSetting('isNotice',value)}"
                  :active-color="getThemeColor" 
                  :active-text="isNotice?$t('common.base.enable'):$t('common.base.disable')">
                </el-switch>

                <el-tooltip v-else :content="$t('task.setting.taskSetting.placeholder5')" placement="top" >
                  <el-switch
                    class="setting—box-switch"
                    v-model="isNotice"
                    :active-color="getThemeColor" 
                    :disabled="true"
                    :active-text="isNotice?$t('common.base.enable'):$t('common.base.disable')">
                  </el-switch>
                </el-tooltip>
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">{{$t('task.setting.taskSetting.text19')}}</p>
                <p class="item-text">
                  <span>{{$t('task.setting.taskSetting.text20')}}</span>
                  <br/>
                  <el-checkbox v-show="allowAutoDispatch" class="item-checkbox" v-model="needApprove" @change="(value)=>{saveTaskPoolSetting('needApprove',value)}">{{$t('task.setting.taskSetting.text21')}}</el-checkbox>
                </p>
              </el-col>
              <el-col :span="8">
                <el-switch
                    v-if="overTime>0||allowAutoDispatch"
                    class="setting—box-switch"
                    v-model="allowAutoDispatch"
                    @change="(value)=>{allowAutoDispatchChange('allowAutoDispatch',value)}"
                    :active-color="getThemeColor" 
                    :active-text="allowAutoDispatch?$t('common.base.enable'):$t('common.base.disable')">
                </el-switch>
                <el-tooltip v-else :content="$t('task.setting.taskSetting.placeholder5')" placement="top" >
                  <el-switch
                    class="setting—box-switch"
                    v-model="allowAutoDispatch"
                    :active-color="getThemeColor" 
                    :disabled="true"
                    :active-text="allowAutoDispatch?$t('common.base.enable'):$t('common.base.disable')">
                  </el-switch>
                </el-tooltip>
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="16">
                <p class="item-title">
                  <el-tooltip :content="$t('task.setting.taskSetting.placeholder6')" placement="top" >
                    <span style="cursor: pointer;" @click="isExamplesShow1=true">{{$t('task.setting.taskSetting.text22')}} <i class="el-icon-info"></i></span>
                  </el-tooltip>
                </p>
                <p class="item-text">{{$t('task.setting.taskSetting.text23')}}</p>
                <div class="demo-image__preview">
                  <el-image 
                    style="width: 200px;"
                    :src="mobileRevenue1" 
                    :preview-src-list="[mobileRevenue1]">
                  </el-image>
                  <div class="item-image-viewer" v-show="isExamplesShow1">
                    <div @click="isExamplesShow1=false"></div>
                    <img :src="mobileRevenue1" />
                  </div>
                </div>
              </el-col>
              <el-col :span="8">
                <el-switch
                    class="setting—box-switch"
                    v-model="encryptionOpen"
                    @change="(value)=>{savetaskPoolEncrption('open',value)}"
                    :active-color="getThemeColor" 
                    :active-text="encryptionOpen?$t('common.base.enable'):$t('common.base.disable')">
                </el-switch>
              </el-col>
              <el-col :span="24" v-show="encryptionOpen">
                <el-table
                  v-loading="loading.encrptionList"
                  class="item-table"
                  :data="encrptionList"
                  :max-height="winHeight"
                  border
                  header-row-class-name="common-list-table-header__v2"
                  style="width: 100%">
                  <el-table-column
                    type="index"
                    :label="$t('common.base.SN')"
                    width="100"
                    align="center"
                    :index="(val)=>val+1">
                  </el-table-column>
                  <el-table-column
                    min-width="100"
                    align="center"
                    prop="taskTypeName"
                    :label="$t('common.task.taskType')">
                  </el-table-column>
                  <el-table-column
                    min-width="100"
                    align="center"
                    show-overflow-tooltip
                    prop="hideFields"
                    :label="$t('task.setting.taskSetting.text24')">
                  </el-table-column>
                  <el-table-column
                    width="100"
                    align="center"
                    :label="$t('common.base.operation')">
                    <template slot-scope="scope">
                      <el-button type="text" @click="setEncryptionShow(scope.row)">{{$t('common.base.set')}}</el-button>
                    </template>
                  </el-table-column>
                </el-table> 
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 工单异常设置弹窗 atart -->
        <base-modal :title="$t('task.setting.taskSetting.text25')" @closed="is_Show='next'" :show.sync="isSetEncryption" width="700px" class="setting-public-dialog">
          <div class="modal_box">
            <div class="item-checkbox-box">
              <div class="item-checkbox-all">
                <el-checkbox :indeterminate="systemEncryptionIndeterminate" v-model="isSystemEncryptionAll" @change="systemEncryptionAllChange">{{$t('common.form.systemWidget')}}</el-checkbox>
              </div>
              <ul class="item-checkbox-list">
                <li v-for="(item,i) in systemEncryptionList" :key="i">
                  <el-checkbox v-model="item.checked" :label="item.displayName"  @change="systemEncryptionChange">{{item.displayName}}</el-checkbox>
                </li>
              </ul>
            </div>
            <div class="item-checkbox-box">
              <div class="item-checkbox-all">
                <el-checkbox :indeterminate="extEncyptionIndeterminate" :disabled="extEncyptionList.length>0?false:true" v-model="isExtEncyptionListAll" @change="extEncyptionAllChange">{{$t('task.components.list.customFields')}}</el-checkbox>
              </div>
              <ul class="item-checkbox-list">
                <li v-for="(item,i) in extEncyptionList" :key="i">
                  <el-checkbox :title="item.displayName" v-model="item.checked" :label="item.displayName"  @change="extEncyptionChange">{{item.displayName}}</el-checkbox>
                </li>
              </ul>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <base-button type="ghost" @event="isSetEncryption = false">{{$t('common.base.close')}}</base-button>
            <base-button type="primary" @event="saveSetEncryption">{{$t('common.base.save')}}</base-button>
          </div>
        </base-modal>
        <!-- 工单异常设置弹窗 end -->
      </div>

      <!-- 派单设置 -->
      <div class="setting-box module-scroll-dispatch">
        <div class="box-title">
          <p>{{$t('task.edit.allotSetting')}}</p>
        </div>
        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">
                <el-tooltip :content="$t('task.setting.taskSetting.placeholder7')" placement="top" >
                  <span>{{$t('task.setting.taskSetting.text26')}} <i class="el-icon-info"></i></span>
                </el-tooltip>
              </p>
              <p class="item-text">{{$t('task.setting.taskSetting.text27')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="allotByExclusiveTag"
                  @change="(value)=>{saveTaskAct('allotByExclusiveTag',value)}"
                  :active-color="getThemeColor" 
                  :active-text="allotByExclusiveTag?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text28')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text29')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskAllotByMap"
                  @change="(value)=>{saveTaskAct('taskAllotByMap',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskAllotByMap?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text30')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text31')}}</p>
              <div class="setting—box-multiple" v-show="workStateConfig">
                <el-select class="multiple-select" v-model="stateBlackList" filterable multiple>
                  <el-option
                    v-for="item in userStateType"
                    :key="item"
                    :label="getUserWorkStateLabel(item)"
                    :value="item">
                  </el-option>
                </el-select>
                <el-button class="multiple-save" type="primary" @click="saveStateBlackList" :disabled="!isStateBlackChange">{{$t('common.base.save')}}</el-button>
              </div>  
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="workStateConfig"
                  @change="(value)=>{saveTaskAct('workStateConfig',value)}"
                  :active-color="getThemeColor" 
                  :active-text="workStateConfig?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text32')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text33')}}</p>
              <div class="setting—box-multiple" v-show="invisibleLocation">
                <!-- <base-select-user-input
                  multiple 
                  :collapse="false"
                  :value="allotBlackList" 
                  @input="updateHideUser"
                >
                </base-select-user-input> -->
                <!-- <biz-remote-select
                  :value="allotBlackList"
                  :remote-method="remoteMethodAllotList"
                  @input="updateHideUser"
                  placeholder="请选择"
                  value-key="userId"
                  multiple
                  filterable
                  remote
                  >
                </biz-remote-select> -->
                <form-user
                  :field="{ displayName:''}"
                  :multiple="true"
                  :canDelete="true"
                  v-model="allotBlackList"
                  :placeholder="$t('common.placeholder.select')"
                />
                <el-button class="multiple-save" type="primary" @click="saveAllotExclude" :disabled="!isAllotBlackChange">{{$t('common.base.save')}}</el-button>
              </div>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="invisibleLocation"
                  @change="(value)=>{saveTaskAct('invisibleLocation',value)}"
                  :active-color="getThemeColor" 
                  :active-text="invisibleLocation?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15" v-if="isProviderManager">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.sendOrderCertificationCheck')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.sendOrderCertificationCheckDesc')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="providerQualificationScreening"
                  @change="(value)=>{providerChange('providerQualificationScreening', value)}"
                  :active-color="getThemeColor"
                  :active-text="providerQualificationScreening?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text102')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text103')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="assignToProviderEngineer"
                  @change="(value)=>{providerChange('ASSIGN_TO_PROVIDER_ENGINEER', value)}"
                  :active-color="getThemeColor"
                  :active-text="assignToProviderEngineer?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text34')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text35')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskRefuse"
                  @change="(value)=>{saveTaskAct('taskRefuse',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskRefuse?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text36')}}</p>
              <p class="item-text">
                  <span>{{$t('task.setting.taskSetting.text37')}}</span>
                  <br/>
                  <el-checkbox v-show="taskReallot" class="item-checkbox" v-model="reallotStateRetain" @change="(value)=>{saveTaskAct('reallotStateRetain',value)}">{{$t('task.setting.taskSetting.text38')}}</el-checkbox>
                </p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskReallot"
                  @change="(value)=>{saveTaskAct('taskReallot',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskReallot?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text39')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text40')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="reallotRemarkNotNull"
                  @change="(value)=>{saveTaskAct('reallotRemarkNotNull',value)}"
                  :active-color="getThemeColor" 
                  :active-text="reallotRemarkNotNull?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <!-- 工单转派时 是否将转派人添加为协同人 start-->
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text98')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text99')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskReallotExecutorAsSyenergies"
                  @change="saveTaskReallotExecutorAsSyenergies"
                  :active-color="getThemeColor" 
                  :active-text="taskReallotExecutorAsSyenergies ? $t('common.base.enable') : $t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <!-- 工单转派时 是否将转派人添加为协同人 end-->

          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text41')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text42')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="autoDispatch"
                  @change="(value)=>{autoDispatchChange('autoDispatch',value)}"
                  :active-color="getThemeColor" 
                  :active-text="autoDispatch?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item module-scroll-assignment" :gutter="15" v-show="autoDispatch">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text43')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text44')}}</p>
            </el-col>
            <el-col :span="8">
              <base-button class="setting-table-addBtn" type="primary" @event="addDispatchRule"><i class="el-icon-plus"></i>{{$t('common.base.create')}}</base-button>
            </el-col>
            <el-col :span="24">

              <!-- 工单分配规则 table -->
              <div class="table-wrapper">
                <table class="table custom-el-table" border bordercolor="#ebeef5">
                  <thead class="thead-dark">
                    <tr>
                      <th scope="col">{{$t('task.setting.taskSetting.text45')}}</th>
                      <th scope="col">{{$t('common.form.type.level')}}</th>
                      <th scope="col">{{$t('common.base.rulerName')}}</th>
                      <th scope="col">{{$t('common.base.operation')}}</th>
                      <th scope="col">{{$t('common.base.enable')}}/{{$t('common.base.disable')}}</th>
                    </tr>
                  </thead>
                  <draggable
                    handle=".moveEle"
                    v-model="dispatchRuleList"
                    v-bind="{
                      animation: 380,
                      ghostClass: 'ghost',
                    }"
                    @change="handleUpdateDispatchRuleListOrder"
                    tag="tbody"
                  >
                    <tr v-for="(item,index) in dispatchRuleList" :key="index">
                      <td class="moveEle"><i class="iconfont icon-tuozhuaipaixu" /></td>
                      <td>{{ index + 1 }}</td>
                      <td>
                        <template v-if="item.name.length <= 20">
                          {{ item.name }}
                        </template>
                        <template v-else>
                          <el-tooltip class="box-item"  :content="item.name" placement="bottom-start">
                            <span>{{ `${item.name.slice(0, 20)}...` }}</span>
                          </el-tooltip>
                        </template>
                      </td>
                      <td>
                        <el-button type="text" @click="editDispatchRule(item, index)">{{$t('common.base.edit')}}</el-button>
                        <!-- TODO 国际化待办 -->
                        <el-button type="text" @click="delDispatchRule(item)" v-if="item.according!='默认规则'">{{$t('common.base.delete')}}</el-button>
                      </td>
                      <td>
                        <!-- TODO 国际化待办 -->
                        <span v-if="item.according === '默认规则'">{{$t('task.setting.taskSetting.open')}}</span>
                        <el-switch
                          v-else
                          :active-text="item.switch ? $t('task.setting.taskSetting.open') : ''"
                          v-model="item.switch"
                          @change="(value)=>{saveDispatchRuleSwitch(item,value)}"
                        />
                      </td>
                    </tr>
                  </draggable>
                </table>
              </div>
            </el-col>
          </el-row>

          <!-- 派单默认设置 start-->
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text93')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text94')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskDefaultAllotSwitch"
                  @change="saveDefaultDispatchMethod"
                  :active-color="getThemeColor" 
                  :active-text="taskDefaultAllotSwitch?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
            <el-row class="box-item"  v-if="taskDefaultAllotSwitch">
              <el-col :span="24">
                <div class="setting—box-multiple default-dispatch-method">
                  <!-- 默认派单方式 -->
                  {{$t('task.setting.taskSetting.text95')}}
                  <el-select
                    style="width: 200px; margin: 0 12px;"
                    v-model="defaultDispatchMethodMap.allotWay"
                    :placeholder="$t('common.placeholder.select')"
                  >
                    <el-option
                      v-for="item in defaultDispatchMethodData"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <template v-if="defaultDispatchMethodMap.allotWay === 'ALLOT'">
                    <!-- 默认派单给 -->
                    {{$t('task.setting.taskSetting.text96')}}
                    <el-select
                      style="width: 200px; margin: 0 12px;"
                      v-model="defaultDispatchMethodMap.defaultExecutor1"
                      :placeholder="$t('common.placeholder.select')"
                    >
                      <el-option
                        v-for="item in defaultDispatchToData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <!-- 或 -->
                    {{$t('task.setting.taskSetting.text97')}}
                    <el-select
                      style="width: 200px; margin: 0 12px;"
                      v-model="defaultDispatchMethodMap.defaultExecutor2"
                      :placeholder="$t('common.placeholder.select')"
                    >
                      <el-option
                        v-for="item in [...defaultDispatchToData, ...defaultDispatchTo2Data]"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                  <el-button class="multiple-save" type="primary" @click="saveDefaultDispatchMethod" :disabled="!isTaskDefaultAllotConfig">{{$t('common.base.save')}}</el-button>
                </div>  
              </el-col>
            </el-row>
          </el-row>
          <!-- 派单默认设置 end-->
        </div>

        <!-- 分配规则弹窗 atart -->
        <base-modal :title="dispatchRuleId?$t('task.setting.taskSetting.text47'):$t('task.setting.taskSetting.text48')" :show.sync="isDispatchRuleModal" width="800px" class="setting-public-dialog">
          <div class="modal_box modal_dispatch" style="padding:25px 80px;">
            <el-form label-position="top" size="mini" :model="dispatchForm" :rules="dispatchRules" ref="dispatchForm" >
              <el-form-item :label="$t('common.base.name')" prop="name">
                <!-- TODO 国际化待办 -->
                <el-input v-model="dispatchForm.name" :disabled="dispatchForm.according=='默认规则'?true:false" :placeholder="$t('task.setting.taskSetting.placeholder8', {data: 10})" maxlength="10"></el-input>
              </el-form-item>
              <!-- TODO 国际化待办 -->
              <el-form-item class="is-required" :label="$t('task.components.allotRuleModal.ruleType')" prop="according" v-show="dispatchForm.according!='默认规则'">
                <el-radio-group v-model="dispatchForm.according" @change="accordingChange">
                  <el-radio-button label="工单类型">{{$t('task.components.allotRuleModal.byTaskType')}}</el-radio-button><!-- byWhat == 'type' -->
                  <el-radio-button label="选择项">{{$t('task.components.allotRuleModal.bySpecialCondition')}}</el-radio-button><!-- byWhat == 'select' -->
                  <el-radio-button label="客户团队">{{$t('task.components.allotRuleModal.byCustomerTag')}}</el-radio-button><!-- byWhat == 'cusTag' -->
                  <el-radio-button label="服务位置">{{$t('task.components.allotRuleModal.byServiceAddress')}}</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <!-- TODO 国际化待办 -->
              <div v-show="dispatchForm.according=='工单类型'">
                <p>{{$t('task.components.allotRuleModal.taskTypeMeetConditions')}}：</p>
                <el-form-item class="is-required" label="">
                  <!-- remote :remote-method="remoteMethodTaskType" -->
                  <el-select v-model="dispatchForm.typeInfo" value-key="id" multiple  filterable :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="item in taskTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <!-- TODO 国际化待办 -->
              <div v-show="dispatchForm.according=='选择项'">
                <p>{{$t('task.components.allotRuleModal.chooseTaskType')}}：</p>
                <el-form-item class="is-required" label="">
                  <!-- remote :remote-method="remoteMethodTaskType" -->
                  <el-select v-model="dispatchForm.template" value-key="id" clearable @change="templateChange" filterable :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="item in taskTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="">
                  <div class="parmes-select-box">
                    <p>{{$t('task.components.allotRuleModal.chooseApplicationConditions')}}</p>
                    <el-select v-model="dispatchForm.fieldName" @change="fieldNameChange">
                      <el-option
                        v-for="item in fieldNameList"
                        :key="item.fieldName"
                        :label="item.displayName"
                        :value="item.fieldName">
                      </el-option>
                    </el-select>
                    <el-select v-model="dispatchForm.operator">
                      <el-option
                        v-for="item in operatorList"
                        :key="item"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                    <el-select v-model="dispatchForm.value" filterable>
                      <el-option
                        v-for="item in valueList"
                        :key="item"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                    <!-- TODO 国际化待办 -->
                    <p>{{$t('common.time.hour')}}</p>
                  </div>
                </el-form-item>
              </div>
              <!-- TODO 国际化待办 -->
              <div v-show="dispatchForm.according=='客户团队'">
                <el-form-item class="is-required" :label="$t('task.setting.taskSetting.text49')">
                  <div class="parmes-select-box">
                    <el-select style="width:88px;margin:0 5px 0 0;" v-model="dispatchForm.operatorContain" :placeholder="$t('common.placeholder.select')">
                      <!-- TODO 国际化待办 -->
                      <el-option value="包含" :label="$t('common.base.include')">{{$t('common.base.include')}}</el-option>
                      <el-option value="不包含" :label="$t('common.base.exclude')">{{$t('common.base.exclude')}}</el-option>
                    </el-select>
                    <p>{{$t('task.setting.taskSetting.text50')}}</p>
                  </div>
                </el-form-item>
                <el-form-item class="is-required" label="">
                  <el-cascader
                    v-model="dispatchForm.tagInfo"
                    @change="tagInfoChange"
                    :options="securityTagTree"
                    filterable
                    :props="{ checkStrictly: true,multiple: true,value:'id',label:'tagName'}"
                    clearable>
                  </el-cascader>
                  <!-- checkStrictly: true ,multiple: true,expandTrigger: 'hover' -->
                </el-form-item>
              </div>
              <!-- TODO 国际化待办 -->
              <el-form-item v-if="dispatchForm.according === '服务位置'" :label="`${$t('task.detail.components.assignTo')}`" prop="serveOption">
                <el-select v-model="dispatchForm.serveOption">
                  <el-option :label="$t('task.components.allotRuleModal.serviceAddressDepartment')" value="servicePositionTag"></el-option>
                  <el-option :label="$t('task.components.allotRuleModal.serviceAddressDepartmentManager')" value="servicePositionTagLeader"></el-option>
                  <el-option v-if="isProviderManager" :label="$t('task.components.allotRuleModal.locationForServiceProvider')" value="serviceProviderPosition"></el-option>
                </el-select>
              </el-form-item>
              <template v-else>
                <el-form-item class="is-required" :label="`${$t('task.detail.components.assignTo')}：`">
                  <el-select v-model="dispatchForm.group" @change="groupChange" :placeholder="$t('common.placeholder.select')">
                    <el-option :label="$t('common.base.userTypes.designatedUser')" value="user"></el-option>
                    <el-option :label="$t('common.base.userTypes.designatedRole')" value="role"></el-option>
                    <el-option :label="$t('common.base.userTypes.designatedService')" value="tag"></el-option>
                    <el-option :label="$t('common.base.userTypes.designatedServiceManager')" value="tagLeader"></el-option>
                    <el-option :label="$t('common.base.userTypes.designatedCustomerManager')" value="customerManager"></el-option>
                    <!-- TODO 国际化待办 -->
                    <el-option v-if="dispatchForm.according=='客户团队'" :label="$t('task.components.allotRuleModal.customerServiceDepartment')" value="cusTagOpt"></el-option>
                    <el-option v-if="dispatchForm.according=='客户团队'" :label="$t('task.components.allotRuleModal.customerServiceDepartmentManager')" value="cusTagLeaderOpt"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item class="is-required" :label="`${$t('common.base.userTypes.designatedUser')}：`" v-show="dispatchForm.group=='user'">
                  <!-- <base-select-user-input
                    multiple 
                    :collapse="false"
                    :value="dispatchForm.info" 
                    @input="updateUser"
                  >
                  </base-select-user-input> -->
                  <!-- <biz-remote-select
                    :value="dispatchForm.info"
                    :remote-method="remoteMethodUser"
                    @input="updateUser"
                    placeholder="请选择"
                    value-key="userId"
                    multiple
                    filterable
                    remote
                  >
                  </biz-remote-select> -->
                  <form-user
                    :field="{ displayName:''}"
                    :multiple="true"
                    :canDelete="true"
                    v-model="dispatchForm.info"
                    :placeholder="$t('common.placeholder.select')"
                  />
                </el-form-item>
                <el-form-item class="is-required" :label="`${$t('common.base.userTypes.designatedRole')}：`" v-show="dispatchForm.group=='role'">

                  <!-- <el-select v-model="dispatchForm.groupId" @change="roleChange" filterable :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="item in roleList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select> -->

                  <!-- start 选择角色 -->
                  <biz-role-select
                    v-model="dispatchForm.groupId"
                    is-only-show-business-service-cloud-role
                    @change="roleChange"
                    filterable
                    :placeholder="$t('common.placeholder.select')"
                    :roles="roleList"
                  >
                  </biz-role-select>
                  <!-- start 选择角色 -->

                </el-form-item>
                <el-form-item class="is-required" :label="`${$t('common.base.userTypes.designatedService')}：`" v-show="dispatchForm.group=='tag'">
                  <el-cascader
                    v-model="dispatchForm.cascaderIds"
                    @change="tagChange"
                    :options="securityTagTree"
                    filterable
                    :props="{ checkStrictly: true,value:'id',label:'tagName'}"
                    clearable>
                  </el-cascader>
                </el-form-item>
                <el-form-item class="is-required"  :label="`${$t('common.base.userTypes.designatedServiceManager')}：`" v-show="dispatchForm.group=='tagLeader'">
                  <el-cascader
                    v-model="dispatchForm.cascaderIds"
                    @change="tagLeaderChange"
                    :options="securityTagTree"
                    filterable
                    :props="{ checkStrictly: true,value:'id',label:'tagName'}"
                    clearable>
                  </el-cascader>
                </el-form-item>
              </template>

              <!-- 指定工作状态 -->
                <el-form-item
                  :label="`${$t('task.components.allotRuleModal.userState')}：`"
                  prop="userState"
                  v-if="isShowUserState"
                >
                  <el-select
                    v-model="dispatchForm.userState"
                    :placeholder="$t('common.placeholder.select')"
                    filterable
                    clearable
                    multiple
                    style="width: 100%"
                    @change="getClassesUserState"
                  >
                    <el-option v-for="(item,index) in userStateOptions" :key="index" :label="item" :value="item"></el-option>
                  </el-select>
                </el-form-item>

              <!-- 班次状态 -->
              <div v-if="isShowSchedulePlan" class="schedule-plan">
                <el-form-item
                  :label="`${$t('task.components.allotRuleModal.designatedShift')}：`"
                  prop="schedulePlan"
                  class="schedule-plan-item"
                >
                  <el-select
                    v-model="dispatchForm.schedulePlan"
                    :placeholder="$t('common.placeholder.select')"
                    filterable
                    clearable
                    multiple
                    style="width: 100%"
                    @change="getClassesStatusMapList"
                  >
                    <el-option v-for="item in schedulePlanList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <div class="schedule-plan-tooltip">
                  <el-tooltip :content="$t('task.setting.taskSetting.placeholder9')" placement="top" >
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </div>
              </div>

              <!-- 派单时间准则 -->
              <div v-if="showDeliveryTime" class="schedule-plan">
                <el-form-item :label="`${$t('task.components.allotRuleModal.allotTimeRule')}：`" prop="scheduleStandard">
                  <el-select v-model="dispatchForm.scheduleStandard" style="width: 100%">
                    <el-option :label="`${$t('task.components.allotRuleModal.matchShiftUserByTaskCreateTime')}：`" value="createTime"></el-option>
                    <el-option :label="`${$t('task.components.allotRuleModal.matchShiftUserByPlanStartTime')}：`" value="planStartTime"></el-option>
                  </el-select>
                </el-form-item>
                <div class="schedule-plan-tooltip">
                  <el-tooltip :content="$t('task.setting.taskSetting.placeholder10')" placement="top" >
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </div>
              </div>
              
              <el-form-item class="is-required" :label="`${$t('task.components.allotRuleModal.allotPriority')}：`" v-show="dispatchForm.group!='customerManager'">
                <el-select v-model="dispatchForm.orderBy" :placeholder="$t('common.placeholder.select')">
                  <el-option :label="$t('task.components.allotRuleModal.lessUnfinishedTaskPriorityAllot')" value="unfinishedTask"></el-option>
                  <el-option :label="$t('task.components.allotRuleModal.closerDistancePriorityAllot')" value="cusDistance"></el-option>
                  <el-option :label="$t('task.components.allotRuleModal.distributeEvenlyInOrder')" value="polling"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <base-button type="ghost" @event="isDispatchRuleModal = false">{{$t('common.base.close')}}</base-button>
            <base-button type="primary" @event="saveDispatchRule('dispatchForm')">{{$t('common.base.save')}}</base-button>
          </div>
        </base-modal>
        <!-- 分配规则弹窗 end -->
      </div>

      <!-- 工单编辑设置 -->
      <div class="setting-box">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.text51')}}</p>
        </div>
        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text52')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text53')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="allowExec2Edit"
                  @change="(value)=>{saveTaskAct('allowExec2Edit',value)}"
                  :active-color="getThemeColor" 
                  :active-text="allowExec2Edit?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text54')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text55')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskSynergy"
                  @change="(value)=>{saveTaskAct('taskSynergy',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskSynergy?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.modifyPlanTime')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text56')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskPlanTime"
                  @change="(value)=>{saveTaskAct('taskPlanTime',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskPlanTime?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text57')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text58')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskRollBack"
                  @change="(value)=>{saveTaskReceipt('taskRollBack',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskRollBack?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text59')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text60')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="editReceipt"
                  @change="(value)=>{saveTaskReceipt('editReceipt',value)}"
                  :active-color="getThemeColor" 
                  :active-text="editReceipt?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text61')}}</p>
              <div class="setting—box-multiple">
                <el-select class="multiple-select" v-model="taskUpdateConfig" multiple>
                  <el-option
                    v-for="item in taskUpdateConfigStates"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-button class="multiple-save" type="primary" @click="saveTaskNonEditableList" :disabled="!isTaskUpdateConfig">{{$t('common.base.save')}}</el-button>
              </div>  
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 工单功能设置 -->
      <div class="setting-box">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.text62')}}</p>
        </div>
        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title" style="margin-bottom:20px">{{$t('task.setting.taskSetting.text63')}}</p>
            </el-col>
            <el-col>
              <el-checkbox v-model="approveRemark" @change="saveApproveRemark">
                {{$t('task.setting.taskSetting.text64')}}
              </el-checkbox>
              <el-checkbox v-model="approveUserRemark" @change="saveApproveUserRemark">
                {{$t('task.setting.taskSetting.text65')}}
              </el-checkbox>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title" style="margin-bottom:20px">{{$t('task.setting.taskSetting.text106')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                class="setting—box-switch"
                v-model="approvalsRequireSignature"
                @change="saveApprovalsRequireSignature"
                :active-color="getThemeColor" 
                :active-text="approvalsRequireSignature ? $t('common.base.enable') : $t('common.base.disable')">
              </el-switch>
            </el-col>
            <el-col :span="24" v-show="approvalsRequireSignature">
              <el-radio-group 
                v-model="useSignature" 
                @change="saveApprovalsRequireSignature"
              >
                <el-radio label="last">{{$t('task.setting.taskSetting.text107')}}</el-radio>
                <el-radio label="new">{{$t('task.setting.taskSetting.text108')}}</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text66')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text67')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="responseWithUrl"
                  @change="(value)=>{saveTaskAct('responseWithUrl',value)}"
                  :active-color="getThemeColor" 
                  :active-text="responseWithUrl?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.shareSetting[0]')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.shareSetting[1]')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskShareForm.insideShareEnable"
                  @change="saveShareConfig"
                  :active-color="getThemeColor" 
                  :active-text="taskShareForm.insideShareEnable?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
            <el-col :span="24" class="share" v-if="taskShareForm.insideShareEnable">
              <el-select class="multiple-select" style="width: 250px; margin-right: 12px" v-model="taskShareForm.insideUserConfig.userTypes" multiple collapse-tags>
                <el-option
                  v-for="item in userType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <div v-if="taskShareForm.insideUserConfig.userTypes.includes('appointUser')" class="share-user-box" @click="selectUser">
					      <div class="share-user">
							    <el-tag
                    v-if="taskShareForm.insideUserConfig.userIds.length"
								    size="small"
								    type='info'
                    style="flex-shrink: 0;"
								    @close="delUser(item.userId)"
                  >
                    {{ taskShareForm.insideUserConfig.userIds[0].displayName }}
							    </el-tag>
                  <el-tag
                    v-if="taskShareForm.insideUserConfig.userIds.length > 1"
								    size="small"
								    type='info'
                    style="margin-left: 6px; flex-shrink: 0;"
								    @close="delUser(item.userId)"
                  >
                    + {{ taskShareForm.insideUserConfig.userIds.length - 1 }}
							    </el-tag>
                  <span class="placeholder" v-if="!taskShareForm.insideUserConfig.userIds.length">{{$t('common.placeholder.selectMember')}}</span>
					      </div>
                <i class="el-icon-arrow-down arrow"></i>
				      </div>
              <el-button class="multiple-save" type="primary" @click="saveShareConfig">{{$t('common.base.save')}}</el-button>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15" v-if="!isBasicEditionControl">
            <el-col :span="16">
              <p class="item-title">
                <el-tooltip :content="$t('task.setting.taskSetting.placeholder6')" placement="top" >
                  <span style="cursor: pointer;" @click="isExamplesShow2=true">{{$t('task.setting.taskSetting.text68')}} <i class="el-icon-info"></i></span>
                </el-tooltip>
              </p>
              <p class="item-text">{{$t('task.setting.taskSetting.text69')}}</p>
              <div class="demo-image__preview">
                <el-image 
                  style="width: 200px;"
                  :src="mobileRevenue2" 
                  :preview-src-list="[mobileRevenue2]">
                </el-image>
                <div class="item-image-viewer" v-show="isExamplesShow2">
                  <div @click="isExamplesShow2=false"></div>
                  <img :src="mobileRevenue2" />
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="mobileShowTaskInfo"
                  @change="(value)=>{saveTaskAct('mobileShowTaskInfo',value)}"
                  :active-color="getThemeColor" 
                  :active-text="mobileShowTaskInfo?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15" v-if="!isBasicEditionHidePay">
            <el-col :span="16">
              <p class="item-title">
                <el-tooltip :content="$t('task.setting.taskSetting.placeholder6')" placement="top" >
                  <span style="cursor: pointer;" @click="isExamplesShow3=true">{{$t('task.setting.taskSetting.text70')}} <i class="el-icon-info"></i></span>
                </el-tooltip>
              </p>
              <p class="item-text">{{$t('task.setting.taskSetting.text71')}}</p>
              <div class="demo-image__preview">
                <el-image 
                  style="width: 200px;"
                  :src="mobileRevenue3" 
                  :preview-src-list="[mobileRevenue3]">
                </el-image>
                <div class="item-image-viewer" v-show="isExamplesShow3">
                  <div @click="isExamplesShow3=false"></div>
                  <img :src="mobileRevenue3" />
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="mobileShowRevenueInfo"
                  @change="(value)=>{saveTaskAct('mobileShowRevenueInfo',value)}"
                  :active-color="getThemeColor" 
                  :active-text="mobileShowRevenueInfo?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text72')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text73')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="appOperateButton"
                  @change="(value)=>{saveTaskAct('appOperateButton',value)}"
                  :active-color="getThemeColor" 
                  :active-text="appOperateButton?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{ $t('task.setting.taskSetting.text104') }}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text105')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                class="setting—box-switch"
                v-model="taskEventAutoFinish"
                @change="saveTaskEventAutoFinish"
                :active-color="getThemeColor" 
                :active-text="taskEventAutoFinish ? $t('common.base.enable') : $t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 工单结算设置 -->
      <div class="setting-box" v-if="!isBasicEditionHidePay">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.text74')}}</p>
        </div>
        <div v-if="openSettleGray" class="box-body customer-settle">
          <span class="JobTip">
            <i18n path="task.setting.taskSetting.text75">
              <span place="data" @click="OpenTab">{{$t('task.setting.taskSetting.text76')}}</span>
            </i18n>
          </span>
        </div>
        <div v-else class="box-body">
          <!-- 灰度控制，原有功能控制 灰度关闭时不显示，灰度开启时显示 -->
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text77')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="openUserDefinedBalance"
                  @change="(value)=>{saveTaskBalanceConfig('openUserDefinedBalance',value)}"
                  :active-color="getThemeColor" 
                  :active-text="openUserDefinedBalance?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <template v-show="openUserDefinedBalance">
            <el-row class="box-item" :gutter="15">
              <el-col :span="24">
                <p class="item-title" style="border-bottom: 1px solid #ddd; padding-bottom:5px;">{{$t('task.setting.taskSetting.text78')}}</p>
              </el-col>
              <el-col :span="24">
                <el-form label-position="top" class="item-form" v-loading="loading.balanceFieldsJson">
                  <el-row v-for="item in balanceFieldsJson.filter(x=>x.isSystem == 0)" :key="item.fieldId">
                    <el-col :span="12">
                      <el-form-item :label="item.displayName+':'">
                        <div v-if="item.formType=='text'">
                          <el-input v-model="item.value" :placeholder="item.placeHolder"></el-input>
                        </div>
                        <div v-else-if="item.formType=='select'">
                          <el-select v-model="item.value" :placeholder="$t('common.placeholder.select')" filterable>
                            <el-option v-for="source in item.setting.dataSource" :key="source" :label="source" :value="source"></el-option>
                          </el-select>
                        </div>
                        <div v-else-if="item.formType=='textarea'">
                          <el-input v-model="item.value" type="textarea" :rows="3" :placeholder="item.placeHolder"></el-input>
                        </div>
                        <div v-else-if="item.formType=='attachment'">
                          <el-upload
                            class="upload-demo"
                            action=""
                            :auto-upload="false"
                            multiple>
                            <el-button size="small" type="primary"><i class="el-icon-plus"></i>{{$t('common.base.addModule', {module: ''})}}</el-button>
                          </el-upload>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-switch
                        class="setting—box-switch"
                        v-model="item.setting.isOpen"
                        @change="(value)=>{saveTaskBalance(item)}"
                        :active-color="getThemeColor" 
                        :active-text="item.setting.isOpen?$t('common.base.enable'):$t('common.base.disable')">
                      </el-switch>
                      <el-button class="balance-setting-btn" type="text" @click="balanceFieldsSettingShow(item)">{{$t('common.base.setting')}}</el-button>
                    </el-col>
                  </el-row>
                </el-form>
              </el-col>
            </el-row>
            <el-row class="box-item" :gutter="15">
              <el-col :span="24">
                <p class="item-title">
                  <el-tooltip :content="$t('task.setting.taskSetting.placeholder10')" placement="top" >
                    <span>{{$t('task.setting.taskSetting.text79')}} <i class="el-icon-info"></i></span>
                  </el-tooltip>
                </p>
                <p class="item-text">
                  <el-select v-model="balanceViewAuthiroty" @change="(value)=>{saveTaskBalanceConfig('balanceViewAuthiroty',true,value)}" :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="item in balanceViewAuthirotyOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </p>
              </el-col>
            </el-row>
          </template>
        </div>

        <!-- 工单结算自定义字段设置弹窗 atart -->
        <base-modal :title="currentBalanceFields.displayName+$t('common.base.setting')" :show.sync="isBalanceFields" width="500px" class="setting-public-dialog">
          <div class="modal_box" style="padding:20px 30px;">
            <el-form label-position="top" size="small" :model="balanceForm" :rules="balanceRules" ref="balanceForm" >
              <div v-if="currentBalanceFields.formType=='text'||currentBalanceFields.formType=='textarea'">
                <p>{{$t('task.setting.taskSetting.placeholder12')}}</p>
                <p style="margin-bottom:20px">{{$t('task.setting.taskSetting.placeholder13')}}</p>
                <el-form-item :label="`${$t('common.base.title')}:`" prop="displayName">
                  <el-input v-model="balanceForm.displayName" maxlength="6"></el-input>
                </el-form-item>
                <el-form-item :label="`${$t('common.form.type.description')}:`">
                  <el-input v-model="balanceForm.placeHolder" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item :label="`${$t('common.base.isRequire')}:`">
                  <el-radio-group v-model="balanceForm.isNull">
                    <el-radio :label="0">{{$t('common.base.yes')}}</el-radio>
                    <el-radio :label="1">{{$t('common.base.no')}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
              <div v-else-if="currentBalanceFields.formType=='select'">
                <p>{{$t('task.setting.taskSetting.placeholder12')}}</p>
                <p style="margin-bottom:20px">{{$t('task.setting.taskSetting.placeholder14')}}</p>
                <el-form-item :label="`${$t('common.base.title')}:`" prop="displayName">
                  <el-input v-model="balanceForm.displayName" maxlength="6"></el-input>
                </el-form-item>
                <el-form-item :label="`${$t('common.base.option')}:`">
                  <el-input type="textarea" :rows="5" v-model="balanceForm.dataSource"></el-input>
                </el-form-item>
                <el-form-item :label="`${$t('common.base.isRequire')}:`">
                  <el-radio-group v-model="balanceForm.isNull">
                    <el-radio :label="0">{{$t('common.base.yes')}}</el-radio>
                    <el-radio :label="1">{{$t('common.base.no')}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
              <div v-else-if="currentBalanceFields.formType=='attachment'">
                <p style="margin-bottom:20px">{{$t('task.setting.taskSetting.placeholder12')}}</p>
                <el-form-item :label="`${$t('common.base.title')}:`" prop="displayName">
                  <el-input v-model="balanceForm.displayName" maxlength="6"></el-input>
                </el-form-item>
              </div>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <base-button type="ghost" @event="isBalanceFields = false">{{$t('common.base.close')}}</base-button>
            <base-button type="primary" @event="saveBalanceForm('balanceForm')">{{$t('common.base.save')}}</base-button>
          </div>
        </base-modal>
        <!-- 工单结算自定义字段设置弹窗 end -->
      </div>

            <!-- 工单里程统计 -->
      <div class="setting-box" v-if="isMileageStatistics">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.taskMileageStatic')}}</p>
        </div>
        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.openTaskMileageStatic')}}</p>
              <p class="item-text">
                {{$t('task.setting.taskSetting.taskMileageStaticExplain')}}
              </p>
            </el-col>
            <el-col :span="8">
              <!-- <el-switch
                class="setting—box-switch"
                v-model="taskMileageSwitch"
                @change="
                  value => {
                    saveTaskBalanceConfig('taskMileageSwitch', value);
                  }
                "
                active-color="#55b7b4"
                :active-text="taskMileageSwitch ? '启用' : '禁用'"
              >
              </el-switch> -->
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="24">
              <p class="item-text">
                {{$t('task.setting.taskSetting.taskMileageCardinalNumber')}}
                <el-select
                  @change="MileageChange"
                  style="width: 200px; margin-left: 12px"
                  v-model="MileageValue"
                  :placeholder="$t('task.setting.taskSetting.selectTaskMileageCardinalNumber')"
                >
                  <el-option :label="$t('task.setting.taskSetting.selectTaskMileageOption[0]')" value="estimatedMileage">
                  </el-option>
                  <el-option :label="$t('task.setting.taskSetting.selectTaskMileageOption[1]')" value="actualMileage">
                  </el-option>
                </el-select>
              </p>
            </el-col>
          </el-row>
        </div>
      </div>


      <!-- 工单备注管理 -->
      <div class="setting-box">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.text80')}}</p>
        </div>

        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text81')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text82')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="taskRemark"
                  @change="(value)=>{saveDdmessage('taskRemark',value)}"
                  :active-color="getThemeColor" 
                  :active-text="taskRemark?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15" v-show="taskRemark">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text83')}}</p>
            </el-col>
            <el-col :span="8">
              <base-button class="setting-table-addBtn" type="primary" @event="addRemark"><i class="el-icon-plus"></i>{{$t('common.base.create')}}</base-button>
            </el-col>
            <el-col :span="24">

              <!-- 工单备注 table -->
              <div class="table-wrapper">
                <table class="table custom-el-table custom-el-table2" border bordercolor="#ebeef5">
                  <thead class="thead-dark">
                    <tr>
                      <th scope="col">{{$t('task.setting.taskSetting.text45')}}</th>
                      <th scope="col">{{$t('common.base.SN')}}</th>
                      <th scope="col">{{$t('task.content')}}</th>
                      <th scope="col">{{$t('common.base.operation')}}</th>
                    </tr>
                  </thead>
                  <draggable
                    handle=".moveEle"
                    v-model="remarkList"
                    v-bind="{
                      animation: 380,
                      ghostClass: 'ghost',
                    }"
                    @change="handleUpdateRemarkListOrder"
                    tag="tbody"
                  >
                    <tr v-for="(item,index) in remarkList" :key="index">
                      <td class="moveEle"><i class="iconfont icon-tuozhuaipaixu" /></td>
                      <td>{{ index + 1 }}</td>
                      <td>
                        <template v-if="item.content.length <= 20">
                          {{ item.content }}
                        </template>
                        <template v-else>
                          <el-tooltip class="item" :content="item.content" placement="bottom-start">
                            <span>{{ `${item.content.slice(0, 20)}...` }}</span>
                          </el-tooltip>
                        </template>
                      </td>
                      <td>
                        <el-button type="text" @click="editRemark(item, index)">{{$t('common.base.edit')}}</el-button>
                        <el-button class="danger-btn" type="text" @click="delRemark(item)">{{$t('common.base.delete')}}</el-button>
                      </td>
                    </tr>
                  </draggable>
                </table>
              </div>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text84')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text85')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="mobileRemarkLocation"
                  @change="(value)=>{saveTaskAct('mobileRemarkLocation',value)}"
                  :active-color="getThemeColor" 
                  :active-text="mobileRemarkLocation?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
        </div>

        <!-- 工单备注弹窗 atart -->
        <base-modal :title="remark.id?$t('task.setting.taskSetting.text86'):$t('task.setting.taskSetting.text87')" :show.sync="isRemarkModal" width="700px" class="setting-public-dialog">
          <div class="modal_box" style="padding:15px 20px; 10px">
            <el-input
              type="textarea"
              :placeholder="$t('task.setting.taskSetting.placeholder15')"
              v-model="remark.content"
              :rows="5"
              maxlength="500">
            </el-input>
            <p class="text-maxlength"><span>{{remark.content.length}}</span>/500</p>
          </div>
          <div slot="footer" class="dialog-footer">
            <base-button type="ghost" @event="isRemarkModal = false">{{$t('common.base.close')}}</base-button>
            <base-button type="primary" @event="saveRemark">{{$t('common.base.save')}}</base-button>
          </div>
        </base-modal>
        <!-- 工单备注弹窗 end -->
      </div>

      <!-- 通过计划任务创建周期性工单 -->
      <div class="setting-box" v-if="isShowPlanTask && !isBasicEditionHidePlanWork">
        <div class="box-title">
          <p>{{$t('task.setting.taskSetting.text88')}}</p>
        </div>
        <div class="box-body">
          <el-row class="box-item" :gutter="15">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text89')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text90')}}</p>
            </el-col>
            <el-col :span="8">
              <el-switch
                  class="setting—box-switch"
                  v-model="enabled"
                  @change="(value)=>{savePlanTask({name:'enabled',value:value})}"
                  :active-color="getThemeColor" 
                  :active-text="enabled?$t('common.base.enable'):$t('common.base.disable')">
              </el-switch>
            </el-col>
          </el-row>
          <el-row class="box-item" :gutter="15" v-show="enabled">
            <el-col :span="16">
              <p class="item-title">{{$t('task.setting.taskSetting.text91')}}</p>
              <p class="item-text">{{$t('task.setting.taskSetting.text92')}}</p>
              <div class="setting—box-multiple">
                <!-- <base-select-user-input
                  multiple 
                  :collapse="false"
                  :value="errorReceivers" 
                  @input="updateAllotUser"
                >
                </base-select-user-input> -->
                <!-- <biz-remote-select
                  :value="errorReceivers"
                  :remote-method="remoteMethodAllotList"
                  @input="updateAllotUser"
                  placeholder="请选择"
                  value-key="userId"
                  multiple
                  filterable
                  remote
                >
                </biz-remote-select> -->
                <form-user
                  :field="{ displayName:''}"
                  :multiple="true"
                  :canDelete="true"
                  v-model="errorReceivers"
                  :placeholder="$t('common.placeholder.select')"
                />
                <el-button class="multiple-save" type="primary" @click="saveErrorReceivers" :disabled="!isErrorReceivers">{{$t('common.base.save')}}</el-button>
              </div>  
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </setting-public-view>
</template>

<script>
/* mixin */
/* api */
import * as SettingApi from '@src/api/SettingApi.ts';
import { getUserInfoByIds } from '@src/api/SystemApi.ts'

/* util */
import Platform, { isOpenData, openAccurateTab } from '@src/util/platform';
import { getRootWindow } from '@src/util/dom';


/* components */
import draggable from 'vuedraggable'
import SettingPublicView from '../../components/settingPublicView';
import { getLocalesOssUrl } from '@src/util/assets'
/* 引用图片 */
const mobileRevenue1 = getLocalesOssUrl('/setting/task/mobileRevenue1.png')
const mobileRevenue2 = getLocalesOssUrl('/setting/task/mobileRevenue2.png')
const mobileRevenue3 = getLocalesOssUrl('/setting/task/mobileRevenue3.png')
/* 工单设置导航 */
import {taskNav} from '../../components/settingPublicView/navList.js';
import { isBasicEditionHidePay, isBasicEditionHideProduct, isBasicEditionHidePlanWork, isBasicEditionControl } from '@shb-lib/version';
import { parse } from '@src/util/querystring';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { TaskExceptionStateLabelEnum, TaskExceptionRangeLabelEnum, UserWorkStateLabelEnum } from '@model/enum/LabelEnum'
import i18n from '@src/locales'
/* mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'task-setting',
  mixins: [VersionControlTaskMixin],
  props: {
    
  },
  data(){
    let check = {
      displayName:(rule, value, callback) => {
        // let reg=/^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
        if(!value){
          callback(new Error(i18n.t('common.base.isRequire')));
        }
        // else if(!reg.test(value)) {
        //   callback(new Error(i18n.t('task.setting.taskSetting.placeholder16')));
        // } 
        else {
          callback();
        }
      }
    };
    return {
      isOpenData,
      current:'task',
      taskNav:taskNav||{},
      //所有设置信息
      configData:{},
      //loading
      loading:{
        page:false,
        encrptionList:false,
        remarkList:false,
        balanceFieldsJson:false
      },
      //工单异常设置
      taskPoolOn:false,//启用工单次
      taskExceptionDialog:false,//工单异常设置弹窗-是否显示
      is_Show:'next',//工单异常设置弹窗-当前显示模块
      tValue: '',//工单异常设置弹窗-异常原因文本编辑
      customTaskExceptionFieldConfig: [],//表格数据
      checkCus: {},//当前选中节点数据
      taskExceptionNodeConfigList: [], // 异常工单节点
      taskExceptionNodeConfigSelect: [], // 当前选中的异常工单节点
      taskExceptionNodeConfigInitial: [], // 初始值
      AbnormalList:[],//异常工单的统计范围
      AbnormalSelect:[],//当前选中的异常工单统计范围
      AbnormalSelectInitial:[],//当前选中的异常工单统计范围初始
      isExamplesShow1:false,//是否显示效果示例图
      mobileRevenue1:mobileRevenue1,//效果示例图路径
      setTaskOperationRequired: true, // 工单操作原因是否必填
      
      //工单池设置
      maxRangeKm:'',//工单池通知距离范围
      maxUsers:'',//工单池通知人数上限
      overTime:'',//工单池超时设置
      byTag:false,
      reallotToPool:false,
      singleDayMaxOrderNum:'',//单日最大接单次数设置
      isNotice:false,//工单池超时提醒 启用/禁用
      allowAutoDispatch:false,//工单池超时自动分配 启用/禁用
      needApprove:false,//派单前需要审批的工单不参与超时自动分配 启用/禁用
      encryptionOpen:false,//工单池接单前隐藏部分 启用/禁用
      encrptionList:[],//工单池接单前隐藏部分字段列表
      winHeight:null,//工单池接单前隐藏部分字段列表高度
      isSetEncryption:false,//工单池接单前隐藏部分字段弹窗是否显示
      currentTaskTypeId:'',//当前配置选中的工单类型id
      systemEncryptionList:[],//系统字段列表
      extEncyptionList:[],//自定义字段列表
      isSystemEncryptionAll:[],//系统字段是否全选
      isExtEncyptionListAll:[],//自定义字段是否全选
      systemEncryptionIndeterminate:false,//系统字段
      extEncyptionIndeterminate:false,//自定义字段

      //派单设置
      allotByExclusiveTag:false,//启用专属服务部门派单模式
      taskAllotByMap:false,//启用地图选人派单
      stateBlackList:[],//指派工单负责人时不显示的用户状态列表
      stateBlackListInitial:[],//初始指派工单负责人时不显示的用户状态列表
      userStateType:[],//用户状态列表
      workStateConfig:false,//隐藏按用户工作状态筛选
      invisibleLocation:false,//隐藏部分人员位置信息
      allotList:[],
      allotBlackList:[],
      allotBlackListInitial:[],
      taskRefuse:false,//允许工单负责人拒绝工单
      reallotStateRetain:false,//转派后保持工单状态不变，无需新负责人再次接受
      taskReallot:false,//允许工单负责人转派工单
      reallotRemarkNotNull:false,//工单转派时是否必填转派说明
      taskReallotExecutorAsSyenergies: false, // 工单转派时是否将转派人添加为协同人
      autoDispatch:false,//启用自动分配规则
      dispatchRuleList:[],//工单分配规则列表
      dispatchRuleId:"",//当前选择的工单分配规则
      isDispatchRuleModal:false,//工单分配规则弹窗是否显示
      taskDefaultAllotSwitch: false, // 开启默认派单设置
      defaultDispatchMethodMap: {
        allotWay: 'ALLOT',
        defaultExecutor1 : '',
        defaultExecutor2: ''
      },
      defaultDispatchToData: [
        { label: i18n.t('task.setting.taskDefaultDispatchSetting.label1'), value: 'CUSTOMER_EXECUTOR' }, // 客户负责人
        { label: i18n.t('task.setting.taskDefaultDispatchSetting.label2'), value: 'TASK_CREATOR' }, // 工单创建任务呢
        { label: i18n.t('task.setting.taskDefaultDispatchSetting.label3'), value: 'ALLOT_USER' }, // 工单派单人
        { label: i18n.t('task.setting.taskDefaultDispatchSetting.label4'), value: 'EVENT_CREATOR' }, // 事件创建人
        { label: i18n.t('task.setting.taskDefaultDispatchSetting.label5'), value: 'LAST_DATA' } // 上次派单结果
      ],
      defaultDispatchTo2Data: [
        { label: i18n.t('task.setting.taskDefaultDispatchSetting.label6'), value: 'NONE' }
      ],
      // TODO 国际化待办
      dispatchForm:{
        name:'',
        according: '工单类型',
        typeInfo:[],
        info:[],
        tagInfo:[],
        group:'user',
        cascaderIds:[],
        groupId:'',
        groupName:'',
        orderBy:'unfinishedTask',
        template:{},
        templateName:'',
        operator:'',
        operatorContain: '包含',
        value:'',
        fieldName:'',
        id:'',
        module:'task',
        serveOption: 'servicePositionTag',
        schedulePlan: [],
        userState:[],
        scheduleStandard: ''
      },
      dispatchRules:{
        name: [
          { required: true,validator: check.displayName, trigger: 'blur' }
        ],
        according: [
          { message: i18n.t('common.placeholder.selectSomething', {0: i18n.t('task.components.allotRuleModal.ruleType')}), trigger: 'change' }
        ],
        serveOption: [
          { required: true, message: i18n.t('common.placeholder.selectSomething', {0: i18n.t('task.detail.components.assignTo')}), trigger: 'change' }
        ],
        scheduleStandard: [
          { required: true, message: i18n.t('common.placeholder.selectSomething', {0: i18n.t('task.components.allotRuleModal.allotTimeRule')}), trigger: 'change' }
        ],
      },
      schedulePlanList: [],
      userStateOptions:[],
      schedulePlanMapList: [],
      enabledFields:[],
      taskTypeList:[],
      userList:[], 
      roleList:[],
      securityTagTree:[],
      valueList:[], 
      operatorList:[], 
      fieldNameList:[],
      providerQualificationScreening: false,
      assignToProviderEngineer: false,

      //工单编辑设置
      allowExec2Edit:false, 
      taskSynergy:false, 
      taskPlanTime:false, 
      taskRollBack:false, 
      editReceipt:false,
      taskUpdateConfig:[],//工单不可编辑的工单状态列表
      taskUpdateConfigInitial:[],//初始工单不可编辑的工单状态列表
      taskUpdateConfigStates:[
        {name:i18n.t('common.task.type.offed'),value:'offed'},
        {name:i18n.t('common.task.type.closed'),value:'closed'},
        {name:i18n.t('common.task.type.finished'),value:'finished'},
        //{name:'已拒绝',value:'refused'},
        {name:i18n.t('common.task.type.costed'),value:'costed'},
        {name:i18n.t('task.taskTypes.review.reviewed'),value:'review'}
      ],

      //工单功能设置
      approveRemark:false, 
      responseWithUrl:false, 
      mobileShowTaskInfo:false, 
      mobileShowRevenueInfo:false, 
      appOperateButton:false, 
      isExamplesShow2:false,//是否显示效果示例图
      isExamplesShow3:false,//是否显示效果示例图
      mobileRevenue2:mobileRevenue2,//效果示例图路径
      mobileRevenue3:mobileRevenue3,//效果示例图路径
      approveUserRemark:false,
      taskEventAutoFinish: false, // 工单完成后关联的事件自动完成
      approvalsRequireSignature: false, // 审批是否需要签名
      useSignature: 'last',

      //工单结算设置
      openUserDefinedBalance:false,//启用工单自定义结算字段
      balanceFieldsJson:[],//工单自定义结算字段列表
      currentBalanceFields:{},//当前工单自定义结算字段
      isBalanceFields:false,//工单自定义结算字段弹窗是否显示
      balanceViewAuthiroty:'',//结算信息查看权限
      balanceViewAuthirotyOptions: [
        {
          value: 'onlyHasBalanceAuthiroty',
          label: i18n.t('task.setting.taskSetting.onlyHasBalanceAuthority')
        }, {
          value: 'hasTaskViewAuthiroty',
          label: i18n.t('task.setting.taskSetting.hasTaskViewAuthority')
        }, {
          value: 'hasTaskEditAuthiroty',
          label: i18n.t('task.setting.taskSetting.hasTaskEditAuthority')
        }
      ],//结算信息查看权限列表
      balanceForm:{
        displayName:'',
        placeHolder:'',
        dataSource:'',
        isNull:'',
      },
      balanceRules:{
        displayName: [
          { validator: check.displayName, trigger: 'blur' }
        ],
      },

      //工单备注管理
      taskRemark:false,//启用工单备注模板
      mobileRemarkLocation:false,//填写备注时，自动获取用户位置
      remarkList:[],//工单备注模板列表
      remark:{
        id:'',//工单备注模板id
        content:'',//工单备注模板内容
        module:''
      },
      isRemarkModal:false,//工单备注模板弹窗是否显示

      //通过计划任务创建周期性工单
      enabled:false,//启用计划任务
      //allUsers:[],
      allUsersObj:{},
      errorReceivers:[],
      errorReceiversInitial:[],
      openSettleGray: false,
      MileageValue:'actualMileage',
      TenantConfig:{},
      isMileageValue:false,
      // 工单分享
      userType: [
        { label: this.$t('task.setting.taskSetting.shareSettingOpt[0]'), value: 'taskExecutor' },
        { label: this.$t('task.setting.taskSetting.shareSettingOpt[1]'), value: 'taskSynergies' },
        { label: this.$t('task.setting.taskSetting.shareSettingOpt[2]'), value: 'taskCreated' },
        { label: this.$t('task.setting.taskSetting.shareSettingOpt[3]'), value: 'taskViewAuth' },
        { label: this.$t('task.setting.taskSetting.shareSettingOpt[4]'), value: 'appointUser' },
      ],
      taskShareForm: {
        insideShareEnable: false,
        insideUserConfig: {
          userTypes: [],
          userIds: [],
        }
      }
    }
  },
  mounted() {
    this.winHeight =window.innerHeight-120;
    // 第一次进入页面获取接口数据后需要滚动到指定区域，添加第二个参数true
    this.getConfigData({},true);//获取设置信息
    this.getTaskExceptionConfig();//获取工单异常设置信息
    this.getBalanceFieldsJson();
    // this.getAllotList();
    this.getTaskPoolEncrption();
    // SettingApi.getAllotUserList().then((res) =>{
    //   console.log(res)
    // })
    this.GetMileageChange();
    this.getTaskShare()
  },
  components: {
    [SettingPublicView.name]: SettingPublicView,
    draggable
  },
  computed: {
    isAbnormalTaskNodeChange(){
      return this.ckeckDifferent(this.taskExceptionNodeConfigSelect, this.taskExceptionNodeConfigInitial)
    },
    isAbnormaChange(){
      return this.ckeckDifferent(this.AbnormalSelect,this.AbnormalSelectInitial);
    },
    isStateBlackChange(){
      return this.ckeckDifferent(this.stateBlackList,this.stateBlackListInitial);
    },
    isAllotBlackChange(){
      return this.ckeckDifferent(this.allotBlackList,this.allotBlackListInitial);
    },
    isTaskUpdateConfig(){
      return this.ckeckDifferent(this.taskUpdateConfig,this.taskUpdateConfigInitial);
    }, 
    isErrorReceivers(){
      return this.ckeckDifferent(this.errorReceivers,this.errorReceiversInitial);
    },
    // 默认派单diff
    isTaskDefaultAllotConfig() {
      return true
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    // 工单里程统计
    isMileageStatistics() {
      return true
    },
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct() 
    },
    // 基础版功能隐藏计划任务
    isBasicEditionHidePlanWork() {
      return isBasicEditionHidePlanWork() 
    },
    //标准版隐藏计划任务
    isShowPlanTask(){
      return this._isShowTaskPlanTask && !this.smartPlanGray
    },
    // 智能计划灰度
    smartPlanGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.SMART_PLAN || false
    },
    // 日历灰度
    isCalendar() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.CALENDER || false
    },
    isBasicEditionControl() {
      return isBasicEditionControl() 
    },
    // 是否开始服务商灰度
    isProviderManager() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.providerManager || false
    },
    // 默认派单方式
    defaultDispatchMethodData() {
      let defaultDispatchList = [
        { label: i18n.t('task.components.taskAllotModal.allotToTaskExecutor'), value: 'ALLOT' },
        { label: i18n.t('task.edit.allotToPool'), value: 'TASK_POOL' },
        { label: i18n.t('task.components.taskAllotModal.allotToServiceProviders'), value: 'SERVICE_PROVIDER' },
        { label: i18n.t('task.detail.components.autoAllot'), value: 'AUTO_DISPATCH' }
      ]
      if (!this.isProviderManager) {
        defaultDispatchList = defaultDispatchList.filter(item => item.value !== 'SERVICE_PROVIDER')
      }
      return defaultDispatchList
    },
     // 显示指定工作状态
    isShowUserState() {
      return this.dispatchForm.group != 'customerManager'
    },
    // 显示班次状态
    isShowSchedulePlan() {
      return this.isCalendar && this.dispatchForm.group != 'customerManager'
    },
    showDeliveryTime() {
      return this.dispatchForm.schedulePlan?.length;
    },
  },
  watch: {
    maxRangeKm(newVal,oldVal){
      if(newVal&&!(newVal-0>=0)){
        this.maxRangeKm=this.configData.taskConfig.poolMaxRange?this.configData.taskConfig.poolMaxRange/1000:'';
      }
    },
    maxUsers(newVal,oldVal){
      if(newVal===0||newVal==="0"){
        this.maxUsers='';
      }else if(newVal){
        this.maxUsers=newVal.toString().replace(/\D/g,'');
      }
    },
    overTime(newVal,oldVal){
      if(newVal&&!(newVal-0>=0)){
        this.overTime=this.configData.taskConfig.poolOverTime == 0?'':this.configData.taskConfig.poolOverTime;
      }
    },
    singleDayMaxOrderNum(newVal,oldVal){
      if(newVal===0||newVal==="0"){
        this.singleDayMaxOrderNum='';
      }else if(newVal){
        this.singleDayMaxOrderNum=newVal.toString().replace(/\D/g,'');
      }
    },
    autoDispatch(newVal,oldVal){
      if(newVal){
        this.getDispatchRuleList();
        this.getWorkNameList(); // 获取班次列表
        this.getWorkStatusList(); // 获取工作状态列表
      }
    },
    taskRemark(newVal,oldVal){
      if(newVal){
        this.getRemarkList();
      }
    },
    isBalanceFields(newVal,oldVal){
      if(!newVal){
        this.$refs.balanceForm.resetFields();
      }
    },
    isDispatchRuleModal(newVal,oldVal){
      if(!newVal){
        this.$refs.dispatchForm.resetFields();
        // TODO 国际化待办
        this.dispatchForm={
          name:'',
          according: '工单类型',
          typeInfo:[],
          info:[],
          tagInfo:[],
          group:'user',
          cascaderIds:[],
          groupId:'',
          groupName:'',
          orderBy:'unfinishedTask',
          template:{},
          templateName:'',
          operator:'',
          operatorContain: '包含',
          value:'',
          fieldName:'',
          id:'',
          module:'task',
          serveOption: 'servicePositionTag',
          schedulePlan: [],
          scheduleStandard: ''
        };
      }
    },
    isBasicEditionHidePay: {
      immediate: true,
      handler(newValue, _) {
        // 基础版过滤以结算选项
        if (newValue) {
          // TODO 国际化待办
          this.taskUpdateConfigStates = this.taskUpdateConfigStates.filter(item => item.name !== '已结算')
        }
      }
    }
  },
  methods: {
    MileageChange(){
      if(this.isMileageValue){
        if(!this.TenantConfig?.taskMileageDataSource?.id) return
        SettingApi.updateTenantConfigById({
          code: 'taskMileageDataSource',
          isOpen: 1,
          configNumValue: 1,
          configStrValue:JSON.stringify([this.MileageValue]) 
        })
        .then(res=>{
          if(res.status === 0){
            this.GetMileageChange()
          }
        })
      }else{
        SettingApi.addTenantConfig({
          configCode:'taskMileageDataSource',
          isOpen: 1,
          configNumValue: 1,
          configStrValue:JSON.stringify([this.MileageValue]) 
        })
        .then(res=>{
          if(res.status === 0){
            this.GetMileageChange()
          }
        })
      }

    },
    GetMileageChange(){
      SettingApi.getTenantConfigByCodeList({
        codeList:['taskMileageDataSource', 'providerQualificationScreening', 'TASK_DEFAULT_ALLOT_TYPE_CONFIG', 'TASK_RE_ALLOT_EXECUTOR_AS_SYNERGIES', 'ASSIGN_TO_PROVIDER_ENGINEER', 'taskEventAutoFinish', 'TASK_APPROVED_SIGN_CONFIG','APPROVE_REMARK','APPROVE_USER_REMARK']}
      ).then(res=>{
        if(res.status === 0){
          res.data.map(item=>{
            this.TenantConfig[item.configCode] = item
            if (item.configCode === 'providerQualificationScreening') {
              this.providerQualificationScreening = item?.isOpen === 1 || false;
            }
            if (item.configCode === 'ASSIGN_TO_PROVIDER_ENGINEER') {
              this.assignToProviderEngineer = item?.isOpen === 1 || false;
            }
          })
          if(this.TenantConfig?.taskMileageDataSource){
            // 有数据用编辑逻辑
            this.isMileageValue = true
            if(this.TenantConfig?.taskMileageDataSource?.configStrValue){
              this.MileageValue = JSON.parse(this.TenantConfig?.taskMileageDataSource?.configStrValue)?.[0]
            }else{
              this.MileageValue ='actualMileage'
            }
          }

          if(this.TenantConfig?.TASK_DEFAULT_ALLOT_TYPE_CONFIG) {
            // 工单派单默认设置
            const taskDefaultAllot = JSON.parse(this.TenantConfig?.TASK_DEFAULT_ALLOT_TYPE_CONFIG?.configStrValue) || {}
            this.taskDefaultAllotSwitch = !!this.TenantConfig?.TASK_DEFAULT_ALLOT_TYPE_CONFIG?.isOpen
            this.defaultDispatchMethodMap = taskDefaultAllot
          }

          if(this.TenantConfig?.TASK_RE_ALLOT_EXECUTOR_AS_SYNERGIES) {
            // 工单转派时 是否将转派人添加为协同人
            this.taskReallotExecutorAsSyenergies = !!this.TenantConfig?.TASK_RE_ALLOT_EXECUTOR_AS_SYNERGIES?.isOpen
          }

          if (this.TenantConfig?.taskEventAutoFinish) {
            // 事件转工单-工单完成时自动完成事件
            this.taskEventAutoFinish = !!this.TenantConfig?.taskEventAutoFinish?.isOpen
          }

          if (this.TenantConfig?.TASK_APPROVED_SIGN_CONFIG) {
            // 审批是否需要签名
            const signatureData = JSON.parse(this.TenantConfig?.TASK_APPROVED_SIGN_CONFIG?.configStrValue) ?? {}
            this.approvalsRequireSignature = signatureData.open; // 审批是否需要签名
            this.useSignature = signatureData.signType || 'last';
          }

          if(this.TenantConfig?.APPROVE_REMARK) {
            // 发起审批是否必填备注信息
            this.approveRemark = !!this.TenantConfig?.APPROVE_REMARK?.isOpen
          }

          if(this.TenantConfig?.APPROVE_USER_REMARK) {
            // 审批人员是否必填备注信息
             this.approveUserRemark = !!this.TenantConfig?.APPROVE_USER_REMARK?.isOpen
          }
        }
      })
    },
    // 默认派单设置 
    saveDefaultDispatchMethod() {
      const defaultDispatch = this.defaultDispatchMethodMap
      const ALLOT = defaultDispatch.allotWay === 'ALLOT'
      let params = {}

      if(!ALLOT) {
        defaultDispatch.defaultExecutor1 = ''
        defaultDispatch.defaultExecutor2 = ''
      }

      // 校验
      if(ALLOT && defaultDispatch.defaultExecutor1 === '' && defaultDispatch.defaultExecutor2 === '') {
        return Platform.alert(this.$t('task.setting.taskSetting.tip26'))
      }

      if(ALLOT && defaultDispatch.defaultExecutor1 === defaultDispatch.defaultExecutor2) {
        return Platform.alert(this.$t('task.setting.taskSetting.tip27'))
      }

      params = {
        code: 'TASK_DEFAULT_ALLOT_TYPE_CONFIG',
        isOpen: Number(this.taskDefaultAllotSwitch) || 0,
        configNumValue: 1,
        configStrValue: JSON.stringify(this.defaultDispatchMethodMap) 
      }

      this.updateTenantConfigById(params)
    },
    // 发起审批是否必填备注信息
    saveApproveRemark() {
      const params = {
        code: 'APPROVE_REMARK',
        isOpen: Number(this.approveRemark) || 0,
        configNumValue: 0,
        configStrValue: null 
      }
      this.updateTenantConfigById(params)
    },
     // 审批人员审批时是否必填备注信息
    saveApproveUserRemark() {
      const params = {
        code: 'APPROVE_USER_REMARK',
        isOpen: Number(this.approveUserRemark) || 0,
        configNumValue: 0,
        configStrValue: null
      }
      this.updateTenantConfigById(params)
    },
    // 审批是否需要签名
    saveApprovalsRequireSignature() {
      const configValue = {
        open: this.approvalsRequireSignature,
        signType: this.useSignature
      }
      const params = {
        code: 'TASK_APPROVED_SIGN_CONFIG',
        isOpen: Number(this.approvalsRequireSignature) || 0,
        configNumValue: 0,
        configStrValue: JSON.stringify(configValue) 
      }
      this.updateTenantConfigById(params)
    },
    // 工单转派时是否将转派人添加为协同人
    saveTaskReallotExecutorAsSyenergies() {
      const params = {
        code: 'TASK_RE_ALLOT_EXECUTOR_AS_SYNERGIES',
        isOpen: Number(this.taskReallotExecutorAsSyenergies) || 0,
        configNumValue: 1 
      }
      this.updateTenantConfigById(params)
    },
    // 工单完成时自动完成事件
    saveTaskEventAutoFinish() {
      const params = {
        code: 'taskEventAutoFinish',
        isOpen: Number(this.taskEventAutoFinish) || 0,
        configNumValue: 0,
      }

      this.updateTenantConfigById(params)
    },
    // 新的配置接口
    updateTenantConfigById(params) {
      this.pageLoading()
      SettingApi.updateTenantConfigById(params)
        .then(res => {
          if(res.status === 0){
            // this.$message.success(this.$t('common.base.tip.operationSuccess'));
            this.GetMileageChange()
          }
        }).catch(err => {
          console.error(err)
        }).finally(() => {
          this.pageLoadingClose()
        })
    },

    OpenTab(){
      // 开启客户结算页面
      // this.$platform.openTab({
      //   close: true,
      //   id: 'SETTLE_MANAGE_CUSTOMER_SETTING',
      //   title: '客户结算',
      //   url: '/pcResourceManage/ServiceSetting/customersetting',
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomersetting,
      })
    },
    /** 工单分配规则排序*/
    handleUpdateDispatchRuleListOrder() {
      const orderList = this.dispatchRuleList.map((rule, idx) => ({
        id: rule.id,
        level: idx + 1,
      }));

      SettingApi.sortDispatchRule(orderList).then((res) =>{
        if(res&&res.status===0){
          this.getDispatchRuleList();
        }else{
          Platform.alert(res.message);
        }
      }).catch((err)=>{
        console.log(err);
      });
    },
    // 查询班次状态列表
		async getWorkNameList() {
			try {
				const { data, success } = await SettingApi.getWorkNameList();
				if(success) {
					this.schedulePlanList = data?.baseWorkNameParamList || [];
				}
			} catch(error) {
				console.error('getWorkNameList', error);
			}
		},
    // 查询工作状态列表
		async getWorkStatusList() {
			try {
				const { data, succ } = await SettingApi.getWorkStatusList();
				if(succ) {
					this.userStateOptions = data?.workTimeConfig?.userStateType || [];
				}
			} catch(error) {
				console.error('getWorkStatusList', error);
			}
		},
    getClassesStatusMapList(value) {
			this.schedulePlanMapList = [];
			value.map(item => {
				const list = this.schedulePlanList.find(list => list.id === item);
				const obj = {
					id: list.id,
					name: list.name,
				};
				this.schedulePlanMapList.push(obj);
			});
		},
    getClassesUserState(){
      this.$forceUpdate()
    },
    /** 工单备注排序*/
    handleUpdateRemarkListOrder() {
      const orderList = this.remarkList.map((rule, idx) => ({
        id: rule.id,
        sequence: idx + 1,
      }));

      this.sortRemark(orderList)
    },
    //获取工单设置信息
    getConfigData(data = {},scroll = false){
       SettingApi.getTenantConfigData().then((res) =>{
          if(res&&res.data){
            this.configDataHandle(res.data,scroll);
          }
        }).catch((err)=>{
          console.log(err)
        });
    },
    async configDataHandle(data={},scroll){
      this.configData=data;
      let {taskConfig={},workTimeConfig={},loginUserConfig={},receiptConfig={},planTaskConfig={},messageConfig={}}=data;
      //工单池设置
      this.taskPoolOn=taskConfig.taskPoolOn;
      this.byTag=taskConfig.poolByTag;
      this.reallotToPool=taskConfig.reallotToPool;
      this.maxRangeKm=taskConfig.poolMaxRange?taskConfig.poolMaxRange/1000:'';
      this.maxUsers=taskConfig.poolMaxUsers ==0?'':taskConfig.poolMaxUsers;
      this.overTime=taskConfig.poolOverTime == 0?'':taskConfig.poolOverTime;
      this.singleDayMaxOrderNum=taskConfig.singleDayMaxOrderNum||'';
      this.isNotice=taskConfig.notice;
      this.allowAutoDispatch=taskConfig.allowAutoDispatch;
      this.needApprove=taskConfig.needApprove;
      this.encryptionOpen=taskConfig.taskPoolEncryptionConfig?.open==1?true:false;
      // if(this.encryptionOpen){
      //   this.getTaskPoolEncrption();
      // }
      //派单设置
      this.allotByExclusiveTag=taskConfig.allotByExclusiveTag;
      this.taskAllotByMap=taskConfig.taskAllotByMap;
      this.workStateConfig = taskConfig.workStateConfig;
      this.invisibleLocation=taskConfig.invisibleLocation;
      this.taskRefuse=taskConfig.taskRefuse;
      this.reallotStateRetain=taskConfig.reallotStateRetain;
      this.taskReallot=taskConfig.taskReallot;
      this.reallotRemarkNotNull=taskConfig.reallotRemarkNotNull;
      this.stateBlackListInitial=workTimeConfig.stateBlackList?[...workTimeConfig.stateBlackList]:[];
      this.stateBlackList=workTimeConfig.stateBlackList?[...workTimeConfig.stateBlackList]:[];
      this.userStateType=workTimeConfig.userStateType?[...workTimeConfig.userStateType]:[];
      
      
      this.autoDispatch=taskConfig.autoDispatch;
      //工单编辑设置
      this.allowExec2Edit=taskConfig.allowExec2Edit;
      this.taskSynergy=taskConfig.taskSynergy;
      this.taskPlanTime=taskConfig.taskPlanTime;
      this.taskRollBack=taskConfig.taskRollBack;
      this.editReceipt=receiptConfig.editReceipt;
      this.taskUpdateConfig=taskConfig.taskUpdateConfig?[...taskConfig.taskUpdateConfig]:[];
      this.taskUpdateConfigInitial=taskConfig.taskUpdateConfig?[...taskConfig.taskUpdateConfig]:[];

      // 基础版过滤以结算的选项值
      if (this.isBasicEditionHidePay) {
        this.taskUpdateConfig = this.taskUpdateConfig.filter(item => item !== 'costed')
      }
     
      //工单功能设置
      this.responseWithUrl=taskConfig.responseWithUrl;
      this.mobileShowTaskInfo=taskConfig.mobileShowTaskInfo;
      this.mobileShowRevenueInfo=taskConfig.mobileShowRevenueInfo;
      this.appOperateButton=taskConfig.appOperateButton;

      //工单结算设置
      this.openUserDefinedBalance=taskConfig.taskBalanceConfig.openUserDefinedBalance;
      this.balanceViewAuthiroty=taskConfig.taskBalanceConfig.balanceViewAuthiroty||'';
      //服务商结算灰度
      this.openSettleGray = taskConfig.settleGray;

      //工单备注管理
      this.taskRemark=messageConfig.taskRemark;
      this.mobileRemarkLocation=taskConfig.mobileRemarkLocation;
      
      //通过计划任务创建周期性工单
      this.enabled=planTaskConfig.enabled;
      // this.errorReceivers=planTaskConfig.errorReceivers.map(x=>x.userId);
      // this.errorReceivers = planTaskConfig.errorReceivers.map(item => this.userErrorSelectConversion(item))
      try {
        if(loginUserConfig?.allotBlackList?.length || planTaskConfig?.errorReceivers?.length){
          let blackListLength = loginUserConfig.allotBlackList.length;
          let errorReceiversIds = planTaskConfig.errorReceivers.map(item=>item.userId);
          let ids = [...loginUserConfig.allotBlackList, ...errorReceiversIds];
          if(!ids.length) {
            throw new Error('数据为空')
          }
          let result = await this.filterUserById(ids);
          // id可能会重复需要根据id重新筛选一遍
          let allotBlackList_ = []
          let errorReceivers_ = [];
          if(blackListLength){
            loginUserConfig.allotBlackList.forEach(item=>{
              let item_ = result.find(v=>v.userId === item);
              if(item_){
                allotBlackList_.push(item_)
              }
            });
          }
          errorReceiversIds.forEach(item=> {
              let item_ = result.find(v=>v.userId === item);
              if(item_){
                errorReceivers_.push(item_)
              }
            });

          this.allotBlackList = allotBlackList_;
          this.errorReceivers = errorReceivers_;
        }
      } catch (error) {
         this.allotBlackList = []
         this.errorReceivers = [];
         console.warn(error, 'try catch allotBlackList && errorReceivers')
      }
      this.errorReceiversInitial=[...this.errorReceivers];
      this.allotBlackListInitial = [...this.allotBlackList];
      
      
      if(!scroll) return;
      this.$nextTick(()=>{
        const { type } = parse(window.location.search) || {};
        if(type) {
          this.scrollToView(`.module-scroll-${type}`);
        }
      })
    },
    // 获取用户工单状态多语言label
    getUserWorkStateLabel(name) {
      return UserWorkStateLabelEnum[name] || name
    },
    scrollToView(className){
      setTimeout(() => {
        const target = document.querySelector(className);
        target && target.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'start',
        });
      }, 500);
    },
    /* 设置 开启/禁用 */
    saveTaskAct(name, state, noMsg) {
      !noMsg && this.pageLoading();
      const params = {
        flow:name,
        state:state
      }
      console.log(params,'params')
      SettingApi.saveTaskAct(params).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //!noMsg && this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          !noMsg && Platform.alert((res&&res.message)? res.message: this.$t('task.setting.taskSetting.settingError'));
        }
        !noMsg && this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        this.pageLoadingClose();
      })
    },
    ckeckDifferent(arr=[],arrInitial=[]){
      let isDifferent=false;
      if(arr.length!==arrInitial.length){
        isDifferent=true;
      }else{
        arr.map(x=>{
          if(arrInitial.indexOf(x)<0){
            isDifferent=true;
          }
        })
      }
      return isDifferent;
    },
    /*--------------------- 工单异常设置 ---------------------*/
    /*获取用户设置 配置*/
    getTaskExceptionConfig() {
      //this.customTaskExceptionFieldConfig = []
      SettingApi.getTaskExceptionConfig().then((res) => {
        //console.log(res,'getTaskExceptionConfig')
        if(res && res.data){
          const {customTaskExceptionFieldConfig, stateTask, taskExceptionNodeConfig} = res.data;
          if (customTaskExceptionFieldConfig) {
            let arr = [];
            for(let key in customTaskExceptionFieldConfig) {
              arr.push(customTaskExceptionFieldConfig[key])
            }
            this.customTaskExceptionFieldConfig = arr.map((item, i) => {
              item['lastList'] = []
              if (item.reason) {
                item.reason.forEach((v, index) => {
                  if (index > 4) {
                    item.lastList.push(v)
                  }
                })
              }
              return item
            })
          }

          this.buildSelectList(stateTask, taskExceptionNodeConfig)

        }
      });
    },
    // 获取工单异常节点的多语言label
    getTaskExceptionStateLabel(name) {
      return TaskExceptionStateLabelEnum[name] || name
    },
    // 获取工单异常节点工单状态的多语言label
    getTaskExceptionRangeLabel(name) {
      return TaskExceptionRangeLabelEnum[name] || name
    },
    buildSelectList(stateTask, taskExceptionNodeConfig) {
      // 统计范围
      let { data: abnormalData, isSelect: abnormalSelect, initial: abnormalInitial } = this.buildExceptionList(stateTask, 'taskExceptionRangeName')
      this.AbnormalList = abnormalData
      this.AbnormalSelect = abnormalSelect
      this.AbnormalSelectInitial = abnormalInitial
      
      // 异常工单
      let { data: exceptionData, isSelect: exceptionSelect, initial: exceptionInitial } = this.buildExceptionList(taskExceptionNodeConfig, 'taskExceptionNodeName')
      this.taskExceptionNodeConfigList = exceptionData
      this.taskExceptionNodeConfigSelect = exceptionSelect
      this.taskExceptionNodeConfigInitial = exceptionInitial

    },
    buildExceptionList(primitiveData, nodeName) {
      if(!primitiveData) return

      let isSelect = []
      let initial = []
      let data = primitiveData.map(item => {
        if(item.switch){
          isSelect.push(item[nodeName])
        }
        return item
      })

      initial = isSelect.map(x => x)
      
      return {
        data,
        isSelect,
        initial
      }
    },
    taskExceptionBtn(even){
      if(even == 'next'){
        let values = this.checkCus.reason ? this.checkCus.reason.join("\n"): ''
        this.tValue = values;
        this.setTaskOperationRequired = !!this.checkCus.notNull
        this.is_Show='save';
      }else{
        // alert('提交');
        const starEvaluateList = this.tValue.split("\n")

        if (starEvaluateList.length > 50) {
            return Platform.alert(this.$t('task.setting.taskSetting.tip1'));
        }

        let num_bool = starEvaluateList.some(item => { return item.length > 60})
        let num_null = starEvaluateList.some(item => { return !item})

        if (num_bool) {
            return Platform.alert(this.$t('task.setting.taskSetting.tip2'));
        }

        if (num_null) {
            return Platform.alert(this.$t('task.setting.taskSetting.tip3'));
        }
        this.saveExceptionTaskReason(starEvaluateList || [])
      }
    },
    /* 保存异常原因 & 工单范围设置*/
    saveExceptionTaskReason(exceptionReason) {
      this.pageLoading();
      const {englishName} = this.checkCus
      const params = {
        fieldName: englishName,
        exceptionReason: exceptionReason,
        notNull: this.setTaskOperationRequired // 异常原因是否必填
      }
      SettingApi.saveExceptionTaskReason(params).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
          this.is_Show='next';
          this.taskExceptionDialog=false;
          this.getTaskExceptionConfig();
        }else{
          Platform.alert((res&&res.message)? res.message:this.$t('task.setting.taskSetting.tip4'));
        }
      }).catch((err)=>{
        console.log(err)
        this.pageLoadingClose();
      })
    },
    /* 异常节点启用/禁用 */
    saveExceptionTaskSwitch(row, value) {
      const params = {
          fieldName: row.englishName,
          isSwitch: value
      }
      SettingApi.saveExceptionTaskSwitch(params).then((res) =>{
        if(!(res&&res.status===0)){
          Platform.alert((res&&res.message)? res.message:(value?this.$t('task.setting.taskSetting.tip5'):this.$t('task.setting.taskSetting.tip6')));
          this.getTaskExceptionConfig();
        }else{
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        }
      }).catch((err)=>{
        this.getTaskExceptionConfig();
      })
    },
    /* 保存选择异常工单的统计范围 */
    saveAbnormalSelect(type){
      if (type === 'taskExceptionNode') { // 异常工单节点设置
        this.saveAbnormalSelectFunction('taskExceptionNode', this.taskExceptionNodeConfigSelect)
      } else if (type === 'taskExceptionRange') { // 异常工单统计范围设置
        this.saveAbnormalSelectFunction('taskExceptionRange', this.AbnormalSelect)
      }
    },
    saveAbnormalSelectFunction(fieldName, exceptionReason) {
      this.pageLoading();
      const params = {
        fieldName,
        exceptionReason
      }
      SettingApi.saveExceptionTaskReason(params).then((res) =>{
        this.pageLoadingClose();
        if(res && res.status === 0){
          this.getTaskExceptionConfig();
        }else{
          Platform.alert((res && res.message) ? res.message : this.$t('task.setting.taskSetting.tip7'));
        }
      })
    },
    /*--------------------- 工单池设置 ---------------------*/
    /* 工单池相关设置发生变动 */
    taskConfigChange(name,value){
      console.log('taskConfigChange',name,value);
      let isSave = true;
      if(name=="maxRangeKm"){
        if(!value&&!this.configData.taskConfig.poolMaxRange){
          return;
        }
        value = (value||0) -0;
      }else if(name=="maxUsers"){
        if(!value&&!this.configData.taskConfig.poolMaxUsers){
          return;
        }
      }else if(name=="overTime"){
        value = (value||0) -0;
        if(!value){
          isSave = false;
          this.$confirm(this.$t('task.setting.taskSetting.tip8'), this.$t('common.base.toast'), {
            confirmButtonText: this.$t('common.base.makeSure'),
            cancelButtonText: this.$t('common.base.cancel'),
            type: 'warning'
          }).then(() => {
            this.saveTaskPoolSetting('overTime', value)
          }).catch(() => {
            this.overTime = this.configData.taskConfig.poolOverTime || ''       
          });
        }else{
          isSave = false;
          this.$confirm(this.$t('task.setting.taskSetting.tip9'), this.$t('common.base.toast'), {
            confirmButtonText: this.$t('common.base.makeSure'),
            cancelButtonText: this.$t('common.base.cancel'),
            type: 'warning'
          }).then(() => {
            this.saveTaskPoolSetting('overTime', value)
          }).catch(() => {
            this.overTime = this.configData.taskConfig.poolOverTime || '';         
          });
        }
      }
      if(isSave){
        this.saveTaskPoolSetting(name,value);
      }
    }, 
    /* 保存工单池相关设置 */
    saveTaskPoolSetting(name,value,noMsg=false){
      !noMsg && this.pageLoading();
      let params={}
      params[name]=value;
      let fnName="saveTaskPoolSetting";
      if(name=="singleDayMaxOrderNum"){
        fnName="saveSingleDayMaxOrderNum"
      }
      SettingApi[fnName](params).then((res) =>{
        if(res&&res.status===0){
          //!noMsg && this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          !noMsg && Platform.alert((res&&res.message)? res.message:this.$t('task.setting.taskSetting.settingError'));
        }
        !noMsg && this.pageLoadingClose();
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        !noMsg && Platform.alert(this.$t('task.setting.taskSetting.settingError'));
        !noMsg && this.pageLoadingClose();
        this.getConfigData();
      })
    },
    /* 修改 工单池超时自动分配 前校验超时时间是否设置*/
    allowAutoDispatchChange(name,value){
      if(value&&!this.autoDispatch){
        this.$confirm(this.$t('task.setting.taskSetting.tip10'), this.$t('common.base.toast'), {
            confirmButtonText: this.$t('common.base.makeSure'),
            cancelButtonText: this.$t('common.base.cancel'),
            type: 'warning'
          }).then(() => {
            this.saveTaskAct('autoDispatch',true,true);
            this.saveTaskAct(name,value);
          }).catch(() => {
            this.allowAutoDispatch=!value;         
          });
      }else{
        this.saveTaskAct(name,value);
      }
    },
    /* 工单池接单前隐藏部分字段功能 启用/禁用 */
    savetaskPoolEncrption(name,value){
      this.pageLoading();
      SettingApi.savetaskPoolEncrption({
        open:value?1:0
      }).then((res) =>{
        this.pageLoadingClose();
        if(res.status == 0){
          //value&&this.getTaskPoolEncrption();
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        } else {
            Platform.alert(res.message||this.$t('task.setting.taskSetting.settingError'));
        }
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        Platform.alert(this.$t('task.setting.taskSetting.settingError'));
        this.pageLoadingClose();
        this.getConfigData();
      })
    },
    /* 获取工单池接单前隐藏部分字段列表数据 */
    getTaskPoolEncrption(){
      this.loading.encrptionList=true;
      SettingApi.getTaskPoolEncrptionFind({}).then((res) =>{
        if(res.status == 0){
          this.encryptionOpen= res.data.open == 1;
          let arr= (res.data && res.data.taskTypeEncryptionList)||[];

          // 基础版过滤产品字段
          if (this.isBasicEditionHideProduct) {
            arr.forEach(item => {
              if (item.encrptionFilesName) {
                // TODO 国际化待办
                item.encrptionFilesName = item.encrptionFilesName.filter(subItem => subItem !== '产品')
              }
            })
          }
          this.encrptionList=arr.map(item=>{
            item.hideFields=this.arrayToString(item.encrptionFilesName,item.taskTypeEncrypt)
            return item;
          })
        }
        this.loading.encrptionList=false;
      }).catch((err)=>{
        this.loading.encrptionList=false;
      })
    },
    arrayToString(arr,taskTypeEncrypt) {
      var res = []
      if(taskTypeEncrypt) {
          res = [this.$t('common.task.taskType')]
      }
      if (arr instanceof Array) {
          res = res.concat(arr)
      }
      return res.join('、');
    },
    /* 获取配置隐藏字段 显示隐藏字段设置弹窗 */
    setEncryptionShow(item){
      this.pageLoading();
      this.currentTaskTypeId = item.taskTypeId;
      SettingApi.getTaskPoolEncrptionList({
        taskTypeId:item.taskTypeId
      }).then((res) =>{
        if(res.status == 0){
          let data=res.data;
          let {systemEncryptionList=[],extEncyptionList=[]}= data||{};
          systemEncryptionList.forEach(item=>{
            item.isSystem = 1;
            item.checked = item.isTick == 1;
          });
          extEncyptionList.forEach(item=>{
              item.isSystem = 0;
              item.checked = item.isTick == 1;
          });
          systemEncryptionList = [
            {
              displayName: this.$t('common.task.taskType'),
              fieldName: "taskType",
              isSystem: 1,
              isTick: data?.taskTypeEncrypt ? 1 : 0,
              checked: data?.taskTypeEncrypt ? true : false,
              typeName: "taskTypeEncrypt"
            },
            ...systemEncryptionList
          ];
          if (this.isBasicEditionHideProduct) {
            // TODO 国际化待办
            systemEncryptionList = systemEncryptionList.filter(item => item.displayName !== '产品')
          }
          this.systemEncryptionList = systemEncryptionList;
          this.extEncyptionList = extEncyptionList;
          console.log(systemEncryptionList,extEncyptionList)
          this.extEncyptionChange();
          this.systemEncryptionChange();
          this.isSetEncryption=true;
        }
        this.pageLoadingClose();
      }).catch((err)=>{
        console.log(err);
        this.pageLoadingClose();
      })
    },
    /* 隐藏字段设置-系统字段全选 */
    systemEncryptionAllChange(val) {
      this.systemEncryptionList.map(x=>{
        x.checked=val;
      });
      this.systemEncryptionIndeterminate = false;
    },
    /* 隐藏字段设置-系统字段选择 */
    systemEncryptionChange(value) {
      let checkedCount = this.systemEncryptionList.filter(x=>x.checked).length;
      this.isSystemEncryptionAll = checkedCount === this.systemEncryptionList.length;
      this.systemEncryptionIndeterminate = checkedCount > 0 && checkedCount < this.systemEncryptionList.length;
    },
    /* 隐藏字段设置-自定义字段全选 */
    extEncyptionAllChange(val) {
      this.extEncyptionList.map(x=>{
        x.checked=val;
      });
      this.extEncyptionIndeterminate = false;
    },
    /* 隐藏字段设置-自定义字段选择 */
    extEncyptionChange(value) {
      let checkedCount = this.extEncyptionList.filter(x=>x.checked).length;
      this.isExtEncyptionListAll = (checkedCount === this.extEncyptionList.length&&checkedCount!=0);
      this.extEncyptionIndeterminate = checkedCount > 0 && checkedCount < this.extEncyptionList.length;
    },
    /* 保存隐藏字段设置 */
    saveSetEncryption(){
      this.pageLoading();
      let taskTypeEncrypt;
      for (let index = 0; index < this.systemEncryptionList.length; index++) {
          const item = this.systemEncryptionList[index];
          if(item.fieldName == 'taskType' && item.typeName == 'taskTypeEncrypt') {
              taskTypeEncrypt = item.checked;
              break;
          }
      }
      let systemEncryptionList = this.systemEncryptionList.filter(item=>item.checked)
      let extEncyptionList = this.extEncyptionList.filter(item=>item.checked)
      let encrptionFiles = [...systemEncryptionList,...extEncyptionList];      
      SettingApi.saveTaskPoolEncrptionFile({
        encrptionFiles:encrptionFiles, 
        taskTypeId: this.currentTaskTypeId, 
        taskTypeEncrypt:taskTypeEncrypt
      }).then((res) =>{
        this.pageLoadingClose();
        if(res.status == 0){
          this.getTaskPoolEncrption();
          this.isSetEncryption=false;
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        } else {
          Platform.alert(data.message||this.$t('task.setting.taskSetting.saveError'));
        }
      }).catch((err)=>{
        console.log(err);
        this.pageLoadingClose();
      })
    },
    /*--------------------- 派单设置 ---------------------*/
    /* 保存选择的指派工单负责人时不显示状态列表 */
    saveStateBlackList(){
      this.pageLoading();
      SettingApi.saveTaskUserState({
        stateBlackList: [...this.stateBlackList]
      }).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          Platform.alert(res.message||this.$t('common.base.saveFail'));
        }
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err);
        this.pageLoadingClose();
        this.getConfigData();
      });
    },
    /* 保存隐藏人员位置信息设置 */
    saveAllotExclude(){
      this.pageLoading();
      let allotListParams = this.allotBlackList.map(item=>item.userId);
      SettingApi.saveAllotExclude({
        allotBlackList: [...allotListParams]
      }).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //this.$notify({ title: '成功',message: res.message,type: 'success'});
        }else{
          Platform.alert((res&&res.message)? res.message:this.$t('common.base.saveFail'));
        }
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err);
        this.pageLoadingClose();
        this.getConfigData();
      });
    },
    /* 是否启用自动分配规则 */  
    autoDispatchChange(name,value){
      if(!value&&this.allowAutoDispatch){
        this.$confirm(this.$t('task.setting.taskSetting.tip11'), this.$t('common.base.toast'), {
            confirmButtonText: this.$t('common.base.makeSure'),
            cancelButtonText: this.$t('common.base.cancel'),
            type: 'warning'
          }).then(() => {
            this.saveTaskAct('allowAutoDispatch',false,true);
            this.saveTaskAct(name,value);
          }).catch(() => {
            this.autoDispatch=!value;         
          });
      }else{
        this.saveTaskAct(name,value);
      }
    },
    /* 查询工单分配规则列表 */ 
    getDispatchRuleList(){
      //this.dispatchRuleList=[];
      this.loading.dispatchRuleList=true;
      SettingApi.getTaskDispatchRules().then((res) =>{
        console.log(res,'查询工单分配规则列表')
        if(res&&res.status===0){
          this.dispatchRuleList=res.data.map(item=>{
            item.switch=item.enabled==1;
            item.loading = false
            item.editButtonText = this.$t('common.base.edit')
            return item;
          });
        }
        this.loading.dispatchRuleList=false;
      }).catch((err)=>{
        console.log(err)
        this.loading.dispatchRuleList=false;
      });
    },
    /* 删除工单分配规则 */ 
    delDispatchRule(item){
      this.$confirm(this.$t('task.setting.taskSetting.tip12'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(() => {
        SettingApi.delDispatchRule({
          id: item.id
        }).then((res) =>{
          if(res&&res.status===0){
            //this.$notify({ title: '成功',message: res.message,type: 'success'});
            this.getDispatchRuleList();
          }else{
            Platform.alert((res&&res.message)? res.message:this.$t('common.base.deleteFail'));
          }
        }).catch((err)=>{
          console.log(err);
          Platform.alert(this.$t('common.base.deleteFail'));
        });
      }).catch(() => {});
    },
    /* 修改工单分配规则列表顺序 */ 
    sortDispatchRule(item,index,type){
      //console.log(item,index,type);
      let arr=this.dispatchRuleList.map((x,i)=>{
        return {id:x.id,level:i};
      })
      let sortNum=0;
      if(type=='up'){
        sortNum=-1;
      }else if(type=='down'){
        sortNum=1;
      }
      let id=arr[index].id;
      arr[index].id=arr[index+sortNum].id;
      arr[index+sortNum].id=id;
      SettingApi.sortDispatchRule(arr).then((res) =>{
        if(res&&res.status===0){
          //this.$notify({ title: '成功',message: res.message,type: 'success'});
          this.getDispatchRuleList();
        }else{
          Platform.alert(res.message);
        }
      }).catch((err)=>{
        console.log(err);
      });
    },
    /* 当前工单分配规则开启/禁用 */ 
    saveDispatchRuleSwitch(row, value) {
      const params = {
        id: row.id,
        enabled: value?1:0
      }
      SettingApi.enableDispatchRule(params).then((res) =>{
        if(!(res&&res.status===0)){
          Platform.alert(res.message||(value?this.$t('task.setting.taskSetting.tip13'):this.$t('task.setting.taskSetting.tip14')));
        }else{
          //this.$notify({ title: '成功',message: res.message,type: 'success'});
        }
        this.getDispatchRuleList();
      }).catch((err)=>{
        this.getDispatchRuleList();
      })
    },
    /*--------------------- 派单设置-规则弹窗 ---------------------*/
    /* 显示新建工单分配规则弹窗 */ 
    addDispatchRule(){
      this.dispatchRuleId='';
      this.getTaskTypeList();
      this.groupChange('user')
      this.isDispatchRuleModal=true;
      this.$nextTick(()=>{})
    },
    /* 显示编辑工单分配规则弹窗 */ 
    async editDispatchRule(item,index){
      this.dispatchRuleList[index]['editButtonText'] = this.$t('common.base.loading')
      this.dispatchRuleList[index]['loading'] = true
      this.dispatchRuleId=item.id;
      this.getTaskTypeList();
      SettingApi.getOneDispatchRule({id:item.id}).then(async (res) =>{
        if(res&&res.status===0){
          let data=res.data;
      
          let obj = Object.assign({},data,data.condition,data.candidate);
          if(obj.info&&obj.info.length>0){
            // obj.info=obj.info.map(x=>x.userId)
            let userList=[...obj.info,...this.userList];
            userList.forEach((item)=>{
              item.userName=item.userName||item.displayName;
            })
            this.userList=this.unique(userList);
          }
          if(obj.typeInfo&&obj.typeInfo.length>0){
            //obj.typeInfo=obj.typeInfo.map(x=>x.id)
            let typeInfoList=[...obj.typeInfo,...this.taskTypeList];
            this.taskTypeList=this.unique(typeInfoList);
          }
          if(obj.templateId){
            obj.template={
              id:obj.templateId,
              name:obj.templateName
            }
          }
          // TODO 国际化待办
          if(obj.according=='客户团队'){
            obj.operatorContain=obj.operator;
            obj.operator='';
          }
          for(let n in this.dispatchForm){
            if(obj[n]){
              this.dispatchForm[n]=obj[n];
            }
          }
          let isUser = data?.condition?.group === 'user';
          if(isUser){
            try{
              let ids = this.dispatchForm.info.map(item=>item.userId);
              this.dispatchForm.info = await this.filterUserById(ids)
            }catch(err){
              this.dispatchForm.info = [];
            }    
          }else{
            this.dispatchForm.info = this.dispatchForm.info.map(item => this.userSelectConversion(item))
          }
          // 工作状态回显
          this.dispatchForm.userState = data.condition.workState || [];
          // 班次状态回显
          this.schedulePlanMapList = data.schedulePlan || [];
          this.dispatchForm.schedulePlan = this.schedulePlanMapList.map(item => +item.id);
          // TODO 国际化待办
          if(obj.according == '服务位置'){
            this.dispatchForm.group = 'user';
            this.dispatchForm.serveOption = data.condition.group;
          }

          this.accordingChange(this.dispatchForm.according,this.dispatchForm.group,obj.tagInfo,obj.fieldName);
          this.groupChange(this.dispatchForm.group,this.dispatchForm.groupId);
          this.dispatchRuleList[index]['editButtonText'] = this.$t('common.base.edit')
          this.dispatchRuleList[index]['loading'] = false
          this.isDispatchRuleModal=true;
        }else{
          Platform.alert(res.message||this.$t('task.setting.taskSetting.tip15'));
        }
      }).catch((err)=>{
        console.log(err);
        Platform.alert(this.$t('task.setting.taskSetting.tip15'));
      });
    },
    /* 保存或编辑工单分配规则 */
    saveDispatchRule(formName){
      this.$refs[formName].validate((valid) => {
        if (!valid) return false;
        let form=this.dispatchForm;
        let params={
          name:form.name,
          module:form.module,
          according:form.according,
          scheduleStandard: form.scheduleStandard,
				  schedulePlan: this.schedulePlanMapList,
          candidate:{},
          condition:{
            workState: this.dispatchForm.userState
          }
        };
        // TODO 国际化待办
        if(form.according=='工单类型'){
          if(form.typeInfo.length<1){
            Platform.alert(this.$t('task.tip.allotRuleTip4'));
            return;
          }
          // params.condition.typeInfo=[];
          // this.taskTypeList.forEach(item=>{
          //   if(form.typeInfo.includes(item.id)){
          //     params.condition.typeInfo.push({id:item.id,name:item.name});
          //   }
          // });
          params.condition.typeInfo=form.typeInfo;
        }else if(form.according=='选择项'){
          if(!(form.fieldName&&form.operator&&form.value)){
            Platform.alert(this.$t('task.setting.taskSetting.tip16'));
            return;
          }
          params.condition.fieldName=form.fieldName;
          params.condition.operator=form.operator;
          params.condition.value=form.value;
          params.condition.templateId=form.template.id;
          params.condition.templateName=form.template.name;
        }else if(form.according=='客户团队'){
          if(form.tagInfo.length<1){
            Platform.alert(this.$t('common.placeholder.selectSomething', {0: this.$t('task.components.allotRuleModal.customerTag')}));
            return;
          }
          params.condition.operator=form.operatorContain;
          let tagInfo=[];
          tagInfo=form.tagInfo.map(item=>{
            let id=item[item.length-1];
            return {
              id:id,
              name:this.cascaderIdsObj[id]
            };
          })
          params.condition.tagInfo=tagInfo;
        }
        params.condition.group=form.group;
        params.condition.orderBy=form.orderBy;

        // TODO 国际化待办
        if(form.according == '服务位置') {
          params.condition.group = form.serveOption;
        }
        let groupMsg={
          role: this.$t('task.setting.taskSetting.tip17'),
          tag: this.$t('task.setting.taskSetting.tip18'),
          tagLeader: this.$t('task.setting.taskSetting.tip19'),
        };
        if(form.group == "user" && form.according !== '服务位置'){
          if(form.info.length<1){
            Platform.alert(this.$t('task.setting.taskSetting.tip20'));
            return;
          }
          params.candidate.info=form.info.map(item=>({userId:item.userId,userName:item.userName||item.displayName,times:0}));
          // this.userList.forEach(item=>{
          //   if(form.info.includes(item.userId)){
          //     params.candidate.info.push({userId:item.userId,userName:item.displayName,times:0});
          //   }
          // });
        }else if(form.group=="role"||form.group=="tag"||form.group=="tagLeader"){
          if(!form.groupId&&form.groupId!==0){
            Platform.alert(groupMsg[form.group]);
            return;
          }
          params.condition.groupId=form.groupId;
          params.condition.groupName=form.groupName;
        }
        console.log('params',params)
        
        let api="saveSettingDispatchRule";
        if(this.dispatchRuleId){
          params.id=this.dispatchRuleId;
          api="updateSettingDispatchRule";
        }
        SettingApi[api](params).then((res) =>{
          if(res&&res.status===0){
            //this.$notify({ title: '成功',message: res.message,type: 'success'});
            this.getDispatchRuleList();
            this.isDispatchRuleModal=false;
          }else{
            Platform.alert(res.message||this.$t('common.base.fail'));
          }
        }).catch((err)=>{
          console.log(err);
          Platform.alert(this.$t('common.base.fail'));
        });
      });
    },
     /* 获取应用条件 */ 
    getEnabledFields(typeId,fieldName){
      this.fieldNameList=[];
      SettingApi.getSettingTaskTypeEnabledFields({
        typeId: typeId||'allSelect',
        tableName: 'task'
      }).then((res) =>{
        this.enabledFields=res;
        let selectFields = [];
        res.forEach((field)=> {
          field.displayName+=(field.setting.isMulti?`(${this.$t('common.base.multiple')})`:`(${this.$t('common.base.radio')})`)
          if(field.fieldName == 'serviceType'){
            selectFields.push(field);
          }else if(field.fieldName == 'serviceContent'){
            selectFields.push(field);
          }else if(field.fieldName == 'level'){
            selectFields.push(field);
          }else if(field.formType == 'select'){
            selectFields.push(field);
          }
        });
        this.fieldNameList=selectFields||[];
        this.dispatchForm.fieldName=this.dispatchForm.fieldName||selectFields[0].fieldName;
        if(fieldName){
          this.fieldNameChange(this.dispatchForm.fieldName,this.dispatchForm.operator,this.dispatchForm.value);
        }else{
          this.fieldNameChange(this.dispatchForm.fieldName);
        }
      })
    },
    getTaskTypeList(pageNum,keyword){
      SettingApi.getSettingTaskTypeList({
        keyword:keyword,
        pageNum:pageNum||1,
        pageSize:500,
      }).then((res) =>{
        let list=res.list||[];
        list=list.map(item=>({id:item.id,name:item.name}));
        list=[...list,...this.taskTypeList];
        this.taskTypeList=this.unique(list);
        console.log('人员列表',res)
      })
    },
    remoteMethodTaskType(query){
      //this.taskTypePageNum
      this.getTaskTypeList(1,query)
    },
    remoteMethodUser(query){
      return this.getUserList(query)
    },
    async getUserList(params){
      try {
        const result = await SettingApi.getSettingUserList(params)

        if (!result || !result.list) return

        result.list = result.list.map(user => this.userSelectConversion(user))
        return result
      } catch(error) {
        console.log(error)
      }
    },
    /**
     * @description 人员select数据转换
    */
    userSelectConversion(user) {
      if(!user) return {}
      
      let { userName, displayName, userId } = user

      return Object.freeze({
        label: userName || displayName,
        value: userId,
        ...user
      })
    },
    /**
     * @description 人员select数据更新
    */
    updateUser(value) {
      this.dispatchForm.info = value
    },
    unique(arr,parme="id") { // 根据唯一标识no来对数组进行过滤
  　　const res = new Map();  //定义常量 res,值为一个Map对象实例
  　　//返回arr数组过滤后的结果，结果为一个数组   过滤条件是，如果res中没有某个键，就设置这个键的值为1
  　　return arr.filter((arr) => !res.has(arr[parme]) && res.set(arr[parme], 1)) 
    },
    accordingChange(value,group='user',tagInfo,fieldName){
      // TODO 国际化待办
      if(value=='选择项'){
        this.getEnabledFields(this.dispatchForm.template.id,fieldName);
      }else{
        this.getSecurityTagTreeData('',tagInfo);
      }
    },
    templateChange(value){
      this.dispatchForm.fieldName='';
      this.dispatchForm.operator='';
      this.dispatchForm.value='';
      // if(!value){
      //   this.dispatchForm.template={};
      // }else{
      //   this.taskTypeList.some(item=>{
      //     if(item.id==value){
      //       this.dispatchForm.templateName=item.name;
      //       return true;
      //     }
      //   })
      // }
      this.getEnabledFields(value.id);
    },
    fieldNameChange(value,operator,value2){
      if(value){
        this.operatorList=[];
        this.valueList=[];
        this.fieldNameList.forEach(item=>{
          if(item.fieldName==value){
            this.valueList=item.setting.dataSource||[];
            if(item.formType == 'select' && item.setting.isMulti){
              this.operatorList=[this.$t('common.base.include'),this.$t('common.base.exclude')];
            }else{
              this.operatorList=[this.$t('common.base.equal'),this.$t('common.base.notEqual')];
           }
          }
        });
        this.dispatchForm.operator=operator||this.operatorList[0];
        this.dispatchForm.value=value2||this.valueList[0];
      }else{
        this.operatorList=[];
        this.valueList=[];
        this.dispatchForm.operator='';
        this.dispatchForm.value='';
        //fieldNameList  operatorList valueList
      }
      console.log(this.dispatchForm)
      this.$nextTick(function () {
      })
    },
    groupChange(value,groupId){
      if(!groupId){
        this.dispatchForm.groupId='';
        this.dispatchForm.groupName='';
      }
      if(value=="user"){
        SettingApi.getSettingUserList({pageNum:1,pageSize:10}).then((res) =>{
          let list=res.list||[];
          list=[...list,...this.userList];
          list.forEach((item)=>{
            item.userName=item.userName||item.displayName;
          })
          this.userList=this.unique(list,'userId');
          console.log('获取user',res)
        })
      }else if(value=="role"){
        SettingApi.getSettingRoleList({pageNum:1,pageSize:500,}).then((res) =>{
          this.roleList=res.list||[];
          console.log('获取role',res)
        })
      }else if(value=="tag"||value=="tagLeader"){
        this.getSecurityTagTreeData(groupId);
      }
    },
    getSecurityTagTreeData(groupId,tagInfo){
      SettingApi.getSettingUserSeeAllOrg().then((res1) =>{
        SettingApi.getSecurityTagTree({seeAllOrg:res1.data,pageNum:1}).then((res2) =>{
          console.log('获取role',res2)
          this.cascaderIdsObj={};
          this.securityTagTree=this.treeSecondaryTreatment(res2.list,groupId);
          if(tagInfo&&tagInfo.length>0){
            this.dispatchForm.tagInfo=[];
            this.updataFormTagInfo(res2.list,tagInfo.map(x=>x.id),[]);
          }
          console.log(this.securityTagTree)
          // let treeText=JSON.stringify(res2.list).replace(/\[\]/g,"null");
          // console.log('获取role2',JSON.parse(treeText))
        })
      })
    },
    updataFormTagInfo(list=[],ids=[],levelID=[]){
      list.forEach(item=>{
        if(ids.includes(item.id)){
          this.dispatchForm.tagInfo.push([...levelID,item.id]);
        }
        if(item.children&&item.children.length>0){
          this.updataFormTagInfo(item.children,ids,[...levelID,item.id]);
        }
      });
    },
    treeSecondaryTreatment(list=[],id='',levelIDs=[]){
      let arr=[];
      list.forEach(item=>{
        if(id&&item.id==id){
          this.dispatchForm.cascaderIds=[...levelIDs,id];
        }
        this.cascaderIdsObj[item.id]=item.tagName;
        let children=null;
        if(item.children&&item.children.length>0){
          children=this.treeSecondaryTreatment(item.children,id,[...levelIDs,item.id]);
        }
        item.children=children;
        arr.push(item)
      });
      return arr;
    },
    roleChange(value){
      // let len=this.roleList.length;
      // for(let i=0;i<len;i++){
      //   if(this.roleList[i].id==value){
      //     this.dispatchForm.groupName=this.roleList[i].name;
      //     break;
      //   }
      // }
      this.roleList.some(item=>{
        if(item.id==value){
          this.dispatchForm.groupName=item.name;
          return true;
        }
      })
    }, 
    tagChange(value){
      if(value.length>0){
        let id=value[value.length-1];
        this.dispatchForm.groupId=id;
        this.dispatchForm.groupName=this.cascaderIdsObj[id];
      }else{
        this.dispatchForm.groupId='';
        this.dispatchForm.groupName='';
      }
      console.log(this.dispatchForm)
    },
    tagLeaderChange(value){
      if(value.length>0){
        let id=value[value.length-1];
        this.dispatchForm.groupId=id;
        this.dispatchForm.groupName=this.cascaderIdsObj[id];
      }else{
        this.dispatchForm.groupId='';
        this.dispatchForm.groupName='';
      }
      console.log(this.dispatchForm)
      
    }, 
    tagInfoChange(value){
      console.log(value)
    }, 
    /*--------------------- 工单编辑设置 ---------------------*/
    saveTaskReceipt(name, state, noMsg) {
      const params = {
        flow:name,
        state:state
      }
      !noMsg && this.pageLoading();
      SettingApi.saveTaskReceipt(params).then((res) =>{
        !noMsg && this.pageLoadingClose();
        if(res&&res.status===0){
          //!noMsg && this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          !noMsg && Platform.alert((res&&res.message)? res.message:this.$t('task.setting.taskSetting.settingError'));
        }
        !noMsg && this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        !noMsg && this.pageLoadingClose();
        !noMsg && Platform.alert(this.$t('task.setting.taskSetting.settingError'));
        !noMsg && this.getConfigData();
      })
    },
    /* 工单处于以下状态之后，不允许对工单再进行编辑 */ 
    saveTaskNonEditableList(){
      this.pageLoading();
      SettingApi.saveTaskUpdate(this.taskUpdateConfig).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          Platform.alert((res&&res.message)? res.message:this.$t('task.setting.taskSetting.settingError'));
        }
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        Platform.alert(this.$t('task.setting.taskSetting.settingError'));
        this.pageLoadingClose();
        this.getConfigData();
      })
    },
    /*--------------------- 工单功能设置 ---------------------*/

    /*--------------------- 工单结算设置 ---------------------*/
    /* 工单结算设置 */ 
    saveTaskBalanceConfig(name, state, data) {
      const params = {
        flow:name,
        state:state
      }
      if(data){
        params.data=data;
      }
      this.pageLoading();
      SettingApi.saveTaskBalanceConfig(params).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          Platform.alert((res&&res.message)? res.message:this.$t('task.setting.taskSetting.settingError'));
        }
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        this.pageLoadingClose();
        Platform.alert(this.$t('task.setting.taskSetting.settingError'));
        this.getConfigData();
      })
    },
    /* 工单结算自定义字段设置列表 */ 
    getBalanceFieldsJson(){
      //this.balanceFieldsJson=[];
      this.loading.balanceFieldsJson=true;
      SettingApi.getTaskBalanceFields().then((res) =>{
        if(res&&res.status===0){
          this.balanceFieldsJson=res.data;
        }
        this.loading.balanceFieldsJson=false;
      }).catch((err)=>{
        console.log(err)
        this.loading.balanceFieldsJson=false;
      });
    },
    /* 保存工单结算自定义字段设置 */
    saveTaskBalance(data,callback) {
      console.log(data)
      const params = {
        data:JSON.stringify(data)
      }
      this.pageLoading();
      SettingApi.saveTaskBalance(params).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          callback && callback(res);
          this.getBalanceFieldsJson();
        }else{
          Platform.alert(res.message||this.$t('task.setting.taskSetting.settingError'));
        }
      }).catch((err)=>{
        console.log(err)
        this.pageLoadingClose();
        Platform.alert(this.$t('task.setting.taskSetting.settingError'));
      })
    },
     /* 工单结算自定义字段设置弹窗显示 */
    balanceFieldsSettingShow(item){
      this.currentBalanceFields=item;
      this.balanceForm.displayName=item.displayName;
      this.balanceForm.placeHolder=item.placeHolder;
      this.balanceForm.dataSource=item.setting.dataSource?item.setting.dataSource.join("\n"):'';
      this.balanceForm.isNull=item.isNull;
      this.isBalanceFields=true;
    },
    saveBalanceForm(formName){
      this.$refs[formName].validate((valid) => {
        if (!valid) return false;
        let balanceForm=this.balanceForm;
        this.currentBalanceFields.displayName=balanceForm.displayName;
        if(this.currentBalanceFields.formType=='text'||this.currentBalanceFields.formType=='textarea'){
          this.currentBalanceFields.placeHolder=balanceForm.placeHolder;
          this.currentBalanceFields.isNull=balanceForm.isNull;
        }else if(this.currentBalanceFields.formType=='select'){
          let dataSource=balanceForm.dataSource.split('\n');
          let dataSource2=[...new Set(dataSource)];
          
          if(dataSource2.length>200){
            Platform.alert(this.$t('task.setting.taskSetting.tip21'));
            return;
          }
          if(dataSource2.some(item=>item.length>20)){
            Platform.alert(this.$t('task.setting.taskSetting.tip22'));
            return;
          }
          this.currentBalanceFields.setting.dataSource=dataSource2;
          this.currentBalanceFields.isNull=balanceForm.isNull;
        }
        console.log(this.currentBalanceFields)
        this.saveTaskBalance(this.currentBalanceFields,(res)=>{
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
          this.isBalanceFields=false;
          this.$refs[formName].resetFields();
        })
      });
    },
    /*--------------------- 工单备注管理 ---------------------*/
    saveDdmessage(name, state) {
      const params = {
        message:name,
        state:state
      }
      this.pageLoading();
      SettingApi.saveTaskDdmessage(params).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          Platform.alert((res&&res.message)? res.message:this.$t('task.setting.taskSetting.settingError'));
        }
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        this.pageLoadingClose();
        Platform.alert(this.$t('task.setting.taskSetting.settingError'));
        this.getConfigData();
      })
    },
    /* 查询工单备注模板列表 */ 
    getRemarkList(){
      // let remarkList=[
      //   {id: "17061", content: "测试1", module: "task"},
      //   {id: "17062", content: "测试2", module: "task"},
      //   {id: "17063", content: "测试3", module: "task"},
      //   {id: "17064", content: "测试4", module: "task"}
      // ];
      //this.remarkList=[];
      this.loading.remarkList=true;
      SettingApi.getTaskRemarkList().then((res) =>{
        console.log(res,'查询工单备注模板列表')
        if(res&&res.status===0){
          this.remarkList=res.data;
        }
        this.loading.remarkList=false;
      }).catch((err)=>{
        console.log(err)
        this.loading.remarkList=false;
      });
    },
    /* 新建工单备注模板弹窗显示 */ 
    addRemark(){
      if(this.remarkList.length >= 50){
        Platform.alert(this.$t('task.setting.taskSetting.tip23'));
        return;
      }
      this.remark.id="";
      this.remark.content="";
      this.remark.module="task";
      this.isRemarkModal=true;
    },
    /* 编辑工单备注模板弹窗显示 */ 
    editRemark(item){
      this.remark.id=item.id;
      this.remark.content=item.content;
      this.remark.module=item.module;
      this.isRemarkModal=true;
    }, 
    /* 保存工单备注模板 */ 
    saveRemark(){
      let remark=this.remark;
      if(!remark.content){
        Platform.alert(this.$t('task.setting.taskSetting.tip24'));
        return;
      }
      let params={
        content:remark.content,
        module:remark.module
      };
      let api="createRemarkContent";
      if(remark.id){
        params.id=this.remark.id;
        api="updateRemarkContent";
      }
      SettingApi[api](params).then((res) =>{
        if(res&&res.status===0){
          //this.$notify({ title: '成功',message: res.message,type: 'success'});
          this.getRemarkList();
          this.isRemarkModal=false;
        }else{
          Platform.alert(res.message||this.$t('common.base.fail'));
        }
      }).catch((err)=>{
        console.log(err);
        Platform.alert(this.$t('common.base.fail'));
      });
    },
    /* 删除工单备注模板 */ 
    delRemark(item){
      this.$confirm(this.$t('task.setting.taskSetting.tip24'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(() => {
        SettingApi.deleteTaskRemark({
          id: item.id
        }).then((res) =>{
          if(res&&res.status===0){
            //this.$notify({ title: '成功',message: res.message,type: 'success'});
            this.getRemarkList();
          }else{
            Platform.alert(res.message||this.$t('common.base.deleteFail'));
          }
        }).catch((err)=>{
          console.log(err);
          Platform.alert(this.$t('common.base.deleteFail'));
        });
      }).catch(() => {});
    }, 
    /* 修改工单备注模板位置 */ 
    sortRemark(params){
      SettingApi.taskEventremarkExchange(params).then((res) =>{
        if(res&&res.status===0){
          //this.$notify({ title: '成功',message: res.message,type: 'success'});
          this.getRemarkList();
        }else{
          Platform.alert(res.message);
        }
      }).catch((err)=>{
        console.log(err);
      });
    },
    /*--------------------- 通过计划任务创建周期性工单 ---------------------*/
    savePlanTask(params) {
      this.pageLoading();
      SettingApi.savePlanTask(params).then((res) =>{
        this.pageLoadingClose();
        if(res&&res.status===0){
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        }else{
          Platform.alert((res&&res.message)? res.message:this.$t('task.setting.taskSetting.settingError'));
        }
        this.getConfigData();
      }).catch((err)=>{
        console.log(err)
        Platform.alert(this.$t('task.setting.taskSetting.settingError'));
        this.pageLoadingClose();
        this.getConfigData();
      })
    },
    getAllUsers(){
      this.allUsers=[
        {userId: "21d39a01-dc47-11ea-879a-00163e0f1a1b", displayName: "阿朱"},
        {userId: "b8a4dc27-d82f-11e8-8abd-7cd30abca02e", displayName: "黄宝成"},
        {userId: "3ed69e40-36af-11ea-9ddd-00163e0f1a1b", displayName: "庞海翠"},
        {userId: "e06d87c0-5d10-11ea-9ddd-00163e0f1a1b", displayName: "叶泽伟"}
      ];
      let allUsersObj={};
      this.allUsers.forEach(item=>{
        allUsersObj[item.userId]=item;
      });
      this.allUsersObj=allUsersObj;
    },
    /**
     * @description: 保存异常提醒设置
     * @param {*}
     */    
    saveErrorReceivers(){
      const params = {
        name:'errorReceivers',
        list:this.errorReceivers
      }
      this.savePlanTask(params);
    },
    remoteMethodAllotList(params) {
      return this.getAllotList(params)
    },
    updateHideUser(value) {
      this.allotBlackList = value
    },
    updateAllotUser(value) {
      this.errorReceivers = value
    },
    /*--------------------- 跨模块 ---------------------*/
    // 获取异常提醒设置人员
    async getAllotList(params = {}){

      try {
        const result = await SettingApi.getErrorAllotUserList(params) 
        if (!result.succ || !result.data.list) return

        result.data.list = result.data.list.map(user => this.userErrorSelectConversion(user))
        return result.data

      } catch(error) {
        console.log(error)
      }
    },
    /**
     * @description 异常提醒设置人员select数据转换
    */
    userErrorSelectConversion(user) {
      if(!user) return {}
      
      let { displayName, userId } = user

      return Object.freeze({
        label: displayName,
        value: userId,
        ...user
      })
    },
    /*--------------------- 其他 ---------------------*/
    /* 全页loading */
    pageLoading(text="loading",spinner="el-icon-loading",background="rgba(255, 255, 255, 0.7)"){
      this.loading.page = this.$loading({
        lock: true,
        text: text,
        spinner: spinner,
        background: background
      });
    },
    pageLoadingClose(){
      this.loading.page.close();
    },
    async filterUserById(ids){
      try{
        let res = await getUserInfoByIds(ids)
        if(res.status){
          throw res
        }
        return Promise.resolve(res.data);
      }catch(err){
        console.warn('try catach erro filterUserById', err)
        return Promise.reject(res)
      }
    },

    async providerChange(key, value) {
      try {
        this.pageLoading();
        let currentItem = this.TenantConfig?.[key]
        let res = await SettingApi.updateTenantConfigById({
          code: key,
          isOpen: value ? 1 : 0,
          configNumValue: currentItem?.configNumValue,
          configStrValue: currentItem?.configStrValue,
        })
        if(!res.success) Platform.alert((res?.message)? res.message:this.$t('task.setting.taskSetting.settingError'));
      } catch (e) {
        console.error(e)
      } finally {
        this.pageLoadingClose();
      }
    },

    /*--------------------- 工单分享设置 ---------------------*/
    // 选择人员
		selectUser() {
			const options = {
				title: this.$t('common.placeholder.selectMember'),
				selectedUsers: this.taskShareForm.insideUserConfig.userIds,
				max: -1,
				unique: false,
				mode: 'filter',
				baseWindowOptions: {
					shadable: true, // 打开遮罩
					minMenu: false, // 最小化
					maxMenu: false, // 最大化
					moveLimit: {
						leftOut: false, // 是否允许左边拖出，true允许
						rightOut: false, // 是否允许右边拖出，true允许
						topOut: false, // 是否允许上边拖出，true允许，此设置不管是false还是true，窗口都不能拖出窗体
						bottomOut: false, // 是否允许下边拖出，true允许
					},
				},
			};

			const rootWindow = getRootWindow(window)

			rootWindow.$fast.select.multi.user(options).then(result => {
				this.taskShareForm.insideUserConfig.userIds = result.data.users
      })
    },
    // 查询工单分享设置
    getTaskShare() {
      SettingApi.getTaskShare().then(res => {
        if(!res.result){return}
        if(!res.result?.insideUserConfig?.userIds?.length){
          this.taskShareForm = res.result
          return
        }
        getUserInfoByIds(res.result.insideUserConfig.userIds).then(res2 => {
          res.result.insideUserConfig.userIds = res2.data
          this.taskShareForm = res.result
        })
      })
    },
    // 保存工单分享设置
    saveShareConfig() {
      const userIds = this.taskShareForm.insideUserConfig.userIds.map(i => i.userId)
      const form = {
        insideShareEnable: this.taskShareForm.insideShareEnable,
        insideUserConfig: {...this.taskShareForm.insideUserConfig, userIds}
      }
      SettingApi.saveTaskShare(form).then(() => {
        // this.$message.success(this.$t('common.base.tip.operationSuccess'));
      })
    },
    // 删除人员
    delUser(id){
      this.taskShareForm.insideUserConfig.userIds = this.taskShareForm.insideUserConfig.userIds.filter(i => i.userId !== id)
    }
  },
  beforeDestroy() {
  }
}
</script>

<style lang="scss">
@import "node_modules/element-ui/packages/theme-chalk/src/image.scss";
@import "node_modules/element-ui/packages/theme-chalk/src/cascader.scss";

</style>
<style lang="scss" scoped>
 .setting-public-dialog {
   .open-data {
    margin-right: 0;
   }
 }
 .setting-box {
  .open-data {
    margin-right: 0;
  }
  .set-task-operation-required {
    height: 36px;
    line-height: 36px;
    font-size: 14px;
  }
 }
 .default-dispatch-method { 
  line-height: 32px;
  padding-left: 7.5px;
 }

 .customer-settle {
   padding-top: 20px;
 }
 .JobTip{
   font-size: 12px;
   font-weight: 400;
   span{
    color:#f59a23; 
    cursor: pointer;
   }
 }
.share {
  display: flex;
  align-items: center;
}
.share-user-box {
  display: inline-block;
  margin-right: 12px;
  border: 1px solid #e0e1e2;
  border-radius: 3px;
  height: 32px;
  padding: 0 30px 0 6px;
  position: relative;
  cursor: pointer;
  .share-user {
    display: flex;
    align-items: center;
    height: 100%;
    padding-right: 11px;
    max-width: 300px;
    overflow: hidden;
    .placeholder {
      color: #8c8c8c;
      font-size: 14px;
      padding-right: 16px;
    }
  }
  .arrow {
    position: absolute;
    right: 8px;
    top: 9px;
    color: #C0C4CC;
  }
  .button-new-tag {
    position: initial;
    height: 24px;
    width: 90px;
    font-size: 12px;
    padding: 1px 6px !important;
  }
}
</style>


<style lang="scss" scoped>
.table-wrapper{
  margin-top: 12px;
  max-height: 450px;
  overflow-y: auto;
  .custom-el-table {
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
    height: fit-content;
    width: 100%;
    max-width: 100%;
    font-size: 14px;
    color: #606266;
    border: 1px solid #ebeef5;
    border-top: 1px solid #fff;
    border-left: 1px solid #fff;
    border-collapse: collapse;
    &.custom-el-table2{
      tr{
        td{
          &:nth-last-of-type(2) {
          width: auto !important;;
        }
        }
      }
    }
    th {
      line-height: 40px;
      text-align: center;
      color: #262626;
      font-weight: 500;
    }
    thead tr {
      background: #fafafa;
    }
    tr {
      height: 40px;
      line-height: 40px;
      td {
        height: 40px;
        padding-left: 8px;
        &:nth-of-type(1) {
          width: 80px;
          text-align: center;
          cursor: move;
        }
        &:nth-of-type(2) {
          width: 80px;
        }
        &:nth-last-of-type(1) {
          width: 148px;
          padding-left: 35px;
        }
        &:nth-last-of-type(2) {
          width: 148px;
          padding-left: 35px;
        }
      }
    }
  }

  .danger-btn {
    color: #ff4d4f !important;
  }
  ::v-deep .ghost {
    border: 1px dashed #ebeef5;
  }
}

.schedule-plan {
  position: relative;
  .schedule-plan-tooltip {
    position: absolute;
    right: -22px;
    top: 34px;
  }
  ::v-deep .schedule-plan-item {
    label {
      // padding-left: 8px;
    }
  }
}

.dialog-footer{
  .base-button{
    &:not(:last-child){
      margin-right:12px
    }
  }
}

</style>

<style lang="scss">
.task-setting-box-warp {
  .base-select-user-input {
    max-width: 506px;
  }
}
</style>